【问题标题】:Using local npm libraries with es6, babel, and webpack通过 es6、babel 和 webpack 使用本地 npm 库
【发布时间】:2018-08-17 06:36:54
【问题描述】:

我遇到了一个问题,这似乎是由于我对 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))/
            }
        ]
    }
};

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

【问题讨论】:

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


    【解决方案1】:

    您可以使用 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 将其安装在每个客户端中,而不是在 service1 和 service2 旁边托管 twilioClient:

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

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

    【讨论】:

    • 太棒了!从来没有想过单独使用 babel。我最终将我的 npm 库保留在原来的位置,但现在一切正常。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 2015-02-03
    • 2016-10-28
    • 2015-08-17
    • 1970-01-01
    相关资源
    最近更新 更多