使用带有es6,babel和webpack的本地npm库

时间:2018-03-08 19:31:41

标签: javascript node.js webpack babeljs babel-loader

我遇到的问题似乎是由于我对webpack缺乏了解。我创建了一个如下所示的文件结构:

|-serverless-cloud-functions
||-my-local-libs
|||-twilioClient
||-service1
||-service2

twilioClient是我创建的库,需要包含在service1和service2中。由于无服务器框架的限制,您无法将文件捆绑到服务之外,因此唯一的选择(我认为)是在服务文件夹中使用npm install ../my-local-libs/twilioClient。这适用于安装模块,但现在它位于node_modules中。目前,我也在使用webpack和babel。

我认为我的根本问题是我的webpack配置如下所示:

const slsw = require("serverless-webpack");
const nodeExternals = require("webpack-node-externals");

module.exports = {
    entry: slsw.lib.entries,
    target: "node",

    externals: [nodeExternals()],

    module: {
        rules: [
            {
                test: /\.js$/,
                loader: "babel-loader",
                exclude: /node_modules/
            }
        ]
    }
};

其中排除了我的es6 twilioClient lib,因为它位于node_modules文件夹中。

我看到有几个人建议这是完成'排除twilioClient之外的节点模块中所有内容的方法:

module.exports = {
    entry: slsw.lib.entries,
    target: "node",

    externals: [nodeExternals()],

    module: {
        rules: [
            {
                test: /\.js$/,
                loader: "babel-loader",
                exclude: /node_modules\/(?!(twilioClient))/
            }
        ]
    }
};

但这在我的情况下不起作用。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用Babel单独编译它,而不是尝试排除twilioClient。这样的事情(在twilioClient目录中):

npx babel src --out-dir lib

twilioClient/package.json中,您可以将main设置为lib/index.js而不是src/index.js,以便导入脚本将获得已编译的版本:

"main": "lib/index.js",

然后,您可以将其推送到github,然后使用npm将其安装在每个客户端中,而不是在twilioClientservice1旁边托管service2

npm install --save http://github.com/your_github_username/twilioclient.git

现在您可以使用twilioClient,就像它是任何其他npm依赖项一样。