Serverless-webpack 不包括 `pg` 包

Serverless-webpack not including `pg` package

我正在尝试修改从 aws-nodejs-typescript 模板生成的代码。我已经安装了 typeormreflect-metadatapg 以使用 PostgreSQL。

他们在 dependenciespackage.json

webpack 配置为默认配置

const path = require('path');
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

/*
This line is only required if you are specifying `TS_NODE_PROJECT` for whatever reason.
 */
// delete process.env.TS_NODE_PROJECT;

module.exports = {
  context: __dirname,
  mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
  entry: slsw.lib.entries,
  devtool: slsw.lib.webpack.isLocal ? 'eval-cheap-module-source-map' : 'source-map',
  resolve: {
    extensions: ['.mjs', '.json', '.ts'],
    symlinks: false,
    cacheWithContext: false,
    plugins: [
      new TsconfigPathsPlugin({
        configFile: './tsconfig.paths.json',
      }),
    ],
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, '.webpack'),
    filename: '[name].js',
  },
  optimization: {
    concatenateModules: false,
  },
  target: 'node',
  externals: [nodeExternals()],
  module: {
    rules: [
      // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
      {
        test: /\.(tsx?)$/,
        loader: 'ts-loader',
        exclude: [
          [
            path.resolve(__dirname, 'node_modules'),
            path.resolve(__dirname, '.serverless'),
            path.resolve(__dirname, '.webpack'),
          ],
        ],
        options: {
          transpileOnly: true,
          experimentalWatchApi: true,
        },
      },
    ],
  },
  plugins: [],
};

问题:sls deploy 之后,zip 存档不包含 pg 包,因此请求失败,因为 Postgres package has not been found installed. Try to install it: npm install pg --save.我该如何解决这个问题?

我怀疑这可能是由于动态依赖项解析或其他原因造成的,因为我的代码中没有直接依赖项,并且 typeorm 根据连接配置中的字符串决定使用哪个驱动程序。

P.S。 sls offline 有效,所以代码应该是正确的,问题出在这个不包含在 zip 存档中的包。

是的,你是对的,可能没有直接依赖关系,你使用了动态需求,即你需要仅在运行时已知的模块。

因此您需要使用以下方法强制添加它:

custom:
  webpack:
    includeModules:
       forceInclude:
         - pg

参见forced inclusion in serverless-webpack