3

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

我看到一些人建议这是完成“排除节点模块中的所有内容twilioClient”的方法:

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

    externals: [nodeExternals()],

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

但这在我的情况下不起作用。任何帮助是极大的赞赏。

4

2 回答 2

0

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

npx babel src --out-dir lib

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

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

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

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

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

于 2018-03-09T00:22:09.153 回答
0

我也遇到过类似的问题,就是在 babel 中使用本地通用包。

如果您不想更改,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转换为node_modulesdir in dist

于 2022-03-05T02:54:31.153 回答