将本地 npm 库与 es6、babel 和 webpack 一起使用

Using local npm libraries with es6, babel, and webpack

我 运行 遇到了一个问题,这似乎是由于我对 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 库,因为它在 node_modules 文件夹中。

我看到几个人建议这是完成的方法'exclude everything in node modules besides twilioClient':

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

    externals: [nodeExternals()],

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

但这对我来说不起作用。非常感谢任何帮助。

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

npx babel src --out-dir lib

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

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

然后不用将 twilioClientservice1service2 一起托管,您可以将其推送到 github,然后使用 npm 在每个客户端中安装它:

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

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

我在babel中使用local common package也遇到过类似的问题

如果您不想更改 main 因为您还主动编辑包并且不想 运行 每次更改时都构建,那么您应该使用下面的babel.config.js

module.exports = function(api) {
  api.cache(true);

  const plugins = [
    '@babel/plugin-transform-modules-commonjs',
  ];

  return {
    plugins,
    ignore: [
      /node_modules\/(?!(your-pkg)\/)/,
    ],
  };
};

这会将 your-pkg 的代码转换为 dist 中的 node_modules 目录。