如何使用`dependOn`从主入口点捆绑单独的应用程序文件?

Posted

技术标签:

【中文标题】如何使用`dependOn`从主入口点捆绑单独的应用程序文件?【英文标题】:how to use `dependOn` to bundle separate application files from the main entry point? 【发布时间】: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 页面。 【参考方案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

【讨论】:

以上是关于如何使用`dependOn`从主入口点捆绑单独的应用程序文件?的主要内容,如果未能解决你的问题,请参考以下文章

如何将整个 Vue 应用程序捆绑为单个 UMD 模块

如何以编程方式将因子捆绑与 browserify 一起使用?

如何单独捆绑供应商脚本并根据需要使用 Webpack?

使用 Rollup 和 Gulp 可以有多个入口点吗?

从主包中获取目录的内容

如何在 iTunes 连接中更改捆绑标识符