You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自动生成本地纯ESM node_modules列表用于Webpack/babel-loader?

自动获取纯ESM node_modules列表,适配Serverless Webpack配置

在为Serverless Framework项目构建CommonJS bundle时,我需要处理仅支持ES6 import/export语法的纯ESM npm包。此前我需要手动在Webpack配置中列出这些包,现在希望能自动生成项目中第三方纯ESM模块及其依赖的列表,无需手动维护,原本打算从遍历package-lock.json入手。

当前Webpack配置示例

const path = require('path');

const babelLoaderExcludeNodeModulesExcept = require('babel-loader-exclude-node-modules-except');
const nodeExternals = require('webpack-node-externals');
const slsw = require('serverless-webpack');

const { isLocal } = slsw.lib.webpack;

// 希望自动生成的纯ESM模块列表
const pureESMModules = ['pretty-ms', 'parse-ms'];

module.exports = {
  target: 'node',
  stats: 'normal',
  entry: slsw.lib.entries,
  externals: [nodeExternals({ allowlist: pureESMModules })],
  mode: isLocal ? 'development' : 'production',
  optimization: { concatenateModules: false },
  resolve: { extensions: ['.js'] },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: babelLoaderExcludeNodeModulesExcept(pureESMModules),
        use: {
          loader: 'babel-loader',
          options: {
            cacheDirectory: true,
          },
        },
      },
    ],
  },
  output: {
    libraryTarget: 'commonjs2',
    filename: '[name].js',
    path: path.resolve(__dirname, '.webpack'),
  },
};

我使用serverless-webpack并设置includeModules为true,确保打包babel-loader转译后的模块:

custom:
  webpack:
    includeModules: true

疑问:是否过度设计?

这功能看起来像是Webpack本该支持的,Webpack或webpack-node-externals无法自动识别纯ESM模块是否有合理原因?我知道babel-loader排除多数模块是为了性能,如果跳过exclude配置会转译所有模块,虽然速度稍慢,但我仍需要这个纯ESM模块列表用于webpack-node-externals的allowlist配置。

编辑补充:自动获取ESM模块的方案

我发现可以用webpack-node-module-types工具获取ESM模块列表,修改后的配置如下:

const { determineModuleTypes } = require('webpack-node-module-types/sync');

// ...

const pureESMModules = determineModuleTypes()?.esm || [];

不过还需要过滤掉仅被devDependencies使用的ESM模块,避免Webpack无法进行摇树优化导致包中出现冗余代码。


内容的提问来源于stack exchange,提问作者Joost Schuur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:06:25