1

在此处输入图像描述

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

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

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


文字代码:

      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. 只需使用moduleResourceas 参考来定义var Eczn(并不精确)
4

1 回答 1

1

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

请注意,我在研究web workersparser 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].

于 2021-02-24T20:23:29.447 回答