【问题标题】:how to use `dependOn` to bundle separate application files from the main entry point?如何使用`dependOn`从主入口点捆绑单独的应用程序文件?
【发布时间】:2021-06-24 10:43:35
【问题描述】:

我有一个后端项目,我想使用 Webpack v5 进行捆绑。

我想将一些文件拆分成它们自己的包并将它们导入到主条目中。

主条目有一个 dependOn 键,其中包含将由主条目使用的文件名数组。

这是webpack.config.json

module.exports = {
  entry: {
    app: {
      import: './index.ts',
      dependOn: 'routes'
    },
    routes: ['./routes.ts']
  },

  output: {
    filename: '[name].js',
    libraryTarget: 'commonjs2',
    path: path.resolve(__dirname, 'build')
  },

  resolve: {
    extensions: ['.ts', '.js']
  },

  target: 'node',

  externals: [
    nodeExternals()
  ],

  mode: 'production',

  optimization: {
    minimize: false,
  },

  module: {
    rules: [{ test: /\.tsx?$/, loader: 'ts-loader' }]
  },

  plugins: [
    new ContextReplacementPlugin(/any-promise/)
  ]
};

运行构建后,会按预期生成两个文件(app.jsroutes.js)。但是当使用 NodeJS 运行入口点时,出现以下错误:webpack_require.C 不存在。

通过documentation 我看到他们的示例dependOn 是基于包而不是单个应用程序文件。

您可以将应用程序文件添加到dependOn 吗?这和模块解析有关系吗?

【问题讨论】:

  • 你是 running the entry point with NodeJS 而不是在你的 HTML 页面中引用这两个?
  • @chenxsan 这是捆绑两个(或更多)单独的应用程序 JS 文件。 app.js 引用 routes.js。没有封装这两个文件的 HTML 页面。

标签: node.js webpack node-modules


【解决方案1】:

假设您已在 app 中导入了 routes,并且您希望将 routes 拆分为单独的捆绑包,而不是包含在捆绑的 app.js 中。

以下是使用 SplitChunksPlugin https://webpack.js.org/plugins/split-chunks-plugin 的方法。

module.exports = {
    entry: {
        app: "./index"
    },
    target: "node",
    optimization: {
        splitChunks: {
            cacheGroups: {
                routes: {
                    filename: "routes.js",
                    test: module => {
                        return module.resource && module.resource.includes("routes");
                    },
                    enforce: true,
                    chunks: "all"
                }
            }
        }
    }
};

Webpack 会输出两个文件,app.jsroutes.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 2016-02-24
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多