Webpack.DefinePlugin.runtimeValue 可以获取模块的入口吗?

can Webpack.DefinePlugin.runtimeValue get the module's entry?

就像这样,使用 DefinePlugin 为我的应用程序定义全局变量 ECZN webpack runtimeValue

并且... WebpackModuleInfo 实际上来自我引用 ECZN 的文件,但我只是得到模块文件路径,而不是 Entry ...

所以,我可以获取 runtimeValue 上下文的条目信息以便为我的多 html 页面应用程序设置不同的 var value 吗?


文本代码:

      new Webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(WEBPACK_NODE_ENV),
        development: JSON.stringify(WEBPACK_NODE_ENV_DEV),
        production: JSON.stringify(WEBPACK_NODE_ENV_PROD),
        ECZN: Webpack.DefinePlugin.runtimeValue((ctx) => {
          console.log('WebpackModuleInfo :: ', ctx.module);
          // @ts-ignore webpack.d.ts doesn't define resource, but it exists on ctx.module acutally
          const moduleResource: unknown = ctx.module.resource;
          if (typeof moduleResource === 'string' && moduleResource.length) {
            const absPathFromCwd = path.relative(cwdResolve('.'), moduleResource);

            return JSON.stringify(absPathFromCwd);
          }
          // throw error if not found
          throw new Error('dynamic');
        }),
      })

我找到了一些解决方案:

  1. 使应用程序具有多个 webpack 配置以创建多个实例,如下所示:https://github.com/webpack/webpack/issues/5546(性能警告)
  2. 只需使用 moduleResource 作为参考来定义 var Eczn(不准确)

我可以想到三种解决方案来获取包含到 module 的导入链的入口点。我将列出所有这些,因为我不确定哪一个最适合您的情况。 Webpack 没有记录这些对象,所以很难说哪个是正确的方法。

请注意,我在 and parser object 的上下文中进行研究时发现了这个问题。


module.parser.state.compilation.entries

module.parser.state.compilation.entries 是一个数组。我猜是因为一个模块可以有多个入口点。我不确定如何使用此方法确定当前入口点,因为我没有要测试的多个入口点。在调试器中对其进行测试。

对于工人:

module.parser.state.compilation.entries[0].resource === '/.../moduleEntryPoint.js'

对于 webpack 配置入口点的文件:

module.parser.state.compilation.entries[0].name === 'main'

# Can have array of `dependencies` if your webpack config entrypoint is an array
module.parser.state.compilation.entries[0].dependencies[*].module.resource === '/.../moduleEntryPoint.js'

module.parser.state.compilation.entries[0].dependencies[*].request === '/.../moduleEntryPoint.js'

解析compilation.name

看起来像这样:

对于工人:

module.parser.state.compilation.name ===
'worker-loader /.../node_modules/babel-loader/lib/index.js??ref--5!/.../node_modules/source-map-loader/index.js!/.../moduleEntryPoint.js'

您可以使用字符串操作来获取入口点。

对于 webpack 配置入口点的文件:

module.parser.state.compilation.name === 'client'

循环 module.issuer 直到 null

对于工人:

while (module.issuer) {
  module = module.issuer
}
module.resource === '/.../moduleEntryPoint.js'

对于 webpack 配置入口点的文件:

while (module.issuer) {
  module = module.issuer
}

module.parser.state.compilation.entries[0].name === 'main'

# Can have array of `dependencies` if your webpack config entrypoint is an array
module.parser.state.compilation.entries[0].dependencies[*].module.resource === '/.../moduleEntryPoint.js'

module.parser.state.compilation.entries[0].dependencies[*].request === '/.../moduleEntryPoint.js'

如果只有一个入口点,issuer module === module.parser.state.compilation.entries[0].