如何在webpack 5或其他方式中配置runtimeChunk与预编译文件路径。

huangapple go评论99阅读模式
英文:

How to configure runtimeChunk with precompiled file path in webpack 5 or alternative

问题

在webpack版本4和node版本14中,runtimeChunkName与预编译块文件路径一起使用,但在webpack 5中不再起作用。

const beforeRenderPath = `before-render/js/dist/BeforeRenderActivity-dyn`;

const runtimeChunkName =
    env === 'development'
      ? `../${beforeRenderPath}`
      : `./plugins/${beforeRenderPath}`;

优化部分如下:

optimization: {
  splitChunks: {
    cacheGroups: {
      antd: {
        name: 'antd',
        test: (module) => {
          return (
            /antd|rc-/.test(module.context) ||
            /ant-design[\\/]icons/.test(module.context)
          );
        },
        chunks: 'all',
        priority: 2,
        enforce: true
      },
      ... some_more_vendors,
    },
    runtimeChunk: {
      name: runtimeChunkName
    }
  }
}

如何在webpack 5中使用文件路径引用来提供runtimeChunk名称?

收到的错误是: 拒绝执行来自的脚本,因为其MIME类型('text/html')不可执行,并且启用了严格的MIME类型检查。

入口点如下所示:

这是从hash映射中提供的插件.json。

{
  "../../conf/login/js/dist/LoginView": "./plugins_on_premise/login/js/LoginView.tsx",
  "../auth-provider/js/dist/AuthProvider": "./plugins_on_premise/auth-provider/js/AuthProvider.ts",
  "../auth-provider/js/dist/RenewTokenActivity-dyn": "./plugins_on_premise/auth-provider/js/RenewTokenActivity-dyn.tsx",
  "../_context-switch/js/dist/ContextSwitchActivity-dyn": "./plugins_on_premise/_context-switch/js/ContextSwitchActivity-dyn.tsx",
  "../change-password/js/dist/ChangePasswordActivity-dyn": "./plugins_on_premise/change-password/js/ChangePasswordActivity-dyn.tsx",
  "../before-render/js/dist/BeforeRenderActivity-dyn": 
  "./plugins/before-render/js/BeforeRenderActivity-dyn.tsx"
}

正在使用的版本如下:

"webpack": "5.88.2",
"webpack-bundle-analyzer": "4.9.0",
"webpack-chunk-rename-plugin": "1.0.3",
"webpack-cli": "5.1.4",
"webpack-dev-middleware": "6.1.1",
"webpack-dev-server": "4.15.1",
"webpack-hot-middleware": "2.25.4"

在webpack 4中,webpack-4中的runtimeChunkName指向特定文件:BeforeRenderActivity,作为依赖项或先前的预检。但webpack 5说,现在需要使用import语法的dependOn。

那么正确的条目语法是什么,以及现在应该保留、删除或修改以从webpack 4继承的runtimeChunkName以获得优化效益?

请求提供一个可工作的示例或修复此问题的步骤。

如何在webpack 5中修复需要一个预编译条目的多个插件入口的问题?

英文:

Earlier in webpack version 4 and node 14 version, runtimeChunkName was with pre-comipled chunk filepath, but now this is not working in webpack 5.

const beforeRenderPath = before-render/js/dist/BeforeRenderActivity-dyn;

const runtimeChunkName =
env === 'development'
? ../${beforeRenderPath}
: ./plugins/${beforeRenderPath};

optimization: {
  splitChunks: {
    cacheGroups: {
      antd: {
        name: 'antd',
        test: (module) => {
          return (
            /antd|rc-/.test(module.context) ||
            /ant-design[\\/]icons/.test(module.context)
          );
        },
        chunks: 'all',
        priority: 2,
        enforce: true
      },
      ... some_more_vendors,
  runtimeChunk: {
    name: runtimeChunkName
  }

How to serve runtimeChunk name with the help of filepath reference in webpack 5?

Error received is: Refused to execute script from because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled

Entry points looks like this:

This is served from plugin.json which is hash map.

{
  "../../conf/login/js/dist/LoginView": "./plugins_on_premise/login/js/LoginView.tsx",
  "../auth-provider/js/dist/AuthProvider": "./plugins_on_premise/auth-provider/js/AuthProvider.ts",
  "../auth-provider/js/dist/RenewTokenActivity-dyn": "./plugins_on_premise/auth-provider/js/RenewTokenActivity-dyn.tsx",
  "../_context-switch/js/dist/ContextSwitchActivity-dyn": "./plugins_on_premise/_context-switch/js/ContextSwitchActivity-dyn.tsx",
  "../change-password/js/dist/ChangePasswordActivity-dyn": "./plugins_on_premise/change-password/js/ChangePasswordActivity-dyn.tsx",
  "../before-render/js/dist/BeforeRenderActivity-dyn": 
  "./plugins/before-render/js/BeforeRenderActivity-dyn.tsx"
}

These are the versions in use:

"webpack": "5.88.2",
"webpack-bundle-analyzer": "4.9.0",
"webpack-chunk-rename-plugin": "1.0.3",
"webpack-cli": "5.1.4",
"webpack-dev-middleware": "6.1.1",
"webpack-dev-server": "4.15.1",
"webpack-hot-middleware": "2.25.4"

runtimeChunkName in webpack-4 was pointing to a specific file: BeforeRenderActivity as a dependency or pre-check earlier. But wepack 5 says, now need to use dependOn with import syntax.

So what should be correct syntax for entries and now going forward runTimeChunkname should be kept or deleted or modified for optimization benefits that was carried from webpack 4.

Requesting a working example or steps to fix this.

How to fix this issue with multiple plugin entry that requires one precompiled entry in webpack 5?

答案1

得分: 1

In Webpack 5, the runtimeChunk behavior has changed, and it now uses the output configuration's filename pattern. To achieve similar behavior to what you were doing in Webpack 4 with runtimeChunkName, you can use the dependOn option along with the import syntax for splitting chunks.

Here's how you can update your configuration:

const beforeRenderPath = './plugins/beforerender/js/dist/BeforeRenderActivity-dyn';

module.exports = {
    optimization: {
        splitChunks: {
            cacheGroups: {
                antd: {
                    // cacheGroups...
                },
            },
        },
        runtimeChunk: {
            name: (entryPoint) => `runtime~${entryPoint.name}`,
        },
    },
    output: {
        // ...other output options...
        filename: (pathData) => {
            if (pathData.chunk.name === 'runtime~main') {
                return 'main.js';
            }
            return '[name].[contenthash].js';
        },
    },
};

For your multiple plugin entries, ensure that each entry specifies its required dependencies using the import syntax. Webpack will handle the chunking and dependencies automatically. Your plugin entries should look something like this:

import 'before-render/js/dist/BeforeRenderActivity-dyn';
import 'auth-provider/js/dist/RenewTokenActivity-dyn';

Make sure that you are using relative paths for the plugin imports, and Webpack will take care of creating the necessary chunks based on the dependencies.

英文:

In Webpack 5, the runtimeChunk behavior has changed, and it now uses the output configuration's filename pattern. To achieve similar behavior to what you were doing in Webpack 4 with runtimeChunkName, you can use the dependOn option along with the import syntax for splitting chunks.

Here's how you can update your configuration:

    const beforeRenderPath = './plugins/beforerender/js/dist/BeforeRenderActivity-dyn';

    module.exports = {
        optimization: {
            splitChunks: {
                cacheGroups: {
                    antd: {
                       // cacheGroups...
                    },
                    runtimeChunk: {
                        name: (entryPoint) => `runtime~${entryPoint.name}`,
                    },
                },
             },
         },
         output: {
    // ...other output options...
    filename: (pathData) => {
      if (pathData.chunk.name === 'runtime~main') {
        return 'main.js';
      }
      return '[name].[contenthash].js';
    },
  },
};

For your multiple plugin entries, ensure that each entry specifies its required dependencies using the import syntax. Webpack will handle the chunking and dependencies automatically. Your plugin entries should look something like this:

import 'before-render/js/dist/BeforeRenderActivity-dyn';
import 'auth-provider/js/dist/RenewTokenActivity-dyn';

Make sure that you are using relative paths for the plugin imports, and Webpack will take care of creating the necessary chunks based on the dependencies.

答案2

得分: 1

我不太确定你在说什么时候的意思 -

runtimeChunkName 与预编译块文件路径一起使用

对于 runtimeChunkv5v4 的文档是相同的,它的唯一效果是将提供的路径附加到为优化生成的运行时模块中,如文档中所述。因此,通过提供类似 ../${beforeRenderPath} 的值,你试图做的是为每个运行时模块加载模块,是吗?

从这个陈述 -

在 webpack-4 中,runtimeChunkName 指向一个特定的文件:BeforeRenderActivity 作为依赖或者在之前进行的预检。但是 webpack 5 说,现在需要使用 import 语法来使用 dependOn。

我认为我上面的猜测是正确的,正如你在对我的评论回复中所提到的,你期望的是为每个运行时模块加载一组特定的模块,而不仅仅是将其中一个共享模块全局包含并在所有地方使用。

共享的入口点应该在运行时加载到所有入口点中,这是你的要求。

要在 Webpack 5 中做到这一点,你需要这样做 -

const env = process.env.NODE_ENV; // 或其他
let beforeRenderPaths = ["before-render/js/dist/BeforeRenderActivity-dyn", "auth-provider/js/dist/RenewTokenActivity-dyn"];

beforeRenderPaths = beforeRenderPaths.map(path => env === "development" ? `../${path}` : `./plugins/${beforeRenderPath}`);

module.exports = {
  //...
  entry: {
    a: { import: "./src/a.js", dependOn: "shared" },
    b: { import: "./src/b.js", dependOn: "shared" },
    c: { import: [ "./src/c.js", "./src/f.js"], dependOn: "shared"},
    'shared': beforeRenderPaths,
  },
  //...
  runtimeChunk: true
};

然后,在所有地方确保导入共享模块,如下所示 -

import 'before-render/js/dist/BeforeRenderActivity-dyn';
import 'auth-provider/js/dist/RenewTokenActivity-dyn';

如果我理解错了或者漏掉了什么,请告诉我。

注意:webpack 不赞成这种做法。阅读 这里 获取更多信息,并查看 这里 了解具体原因。我猜测你的用例是在加载任何东西之前做一些类似认证、检查活动计划等方面的一些事情。

英文:

I'm not quite sure of what you mean when you say -

> runtimeChunkName was with pre-comipled chunk filepath

The documentation for v5 and v4 for runtimeChunk is same and the only effect this takes is appending the provided path to the runtime module generated for optimization, as mentioned in the docs. So by providing a value like ../${beforeRenderPath} what you were trying to do is load the module, one directory up for each runtime module?

From the statement -

> runtimeChunkName in webpack-4 was pointing to a specific file: BeforeRenderActivity as a dependency or pre-check earlier. But wepack 5 says, now need to use dependOn with import syntax.

I think my speculation above is correct and as mentioned by you in response to my comment on the post, what you're expecting is to load a specific set of modules for every runtime module, instead of just having one of those shared module included globally and be used everywhere.

> The shared entry point should be loaded for all entry points in runtime and thats the ask.

To do that in Webpack 5, here's what you'll need to do -

const env = process.env.NODE_ENV; // or whatever
let beforeRenderPaths = ["before-render/js/dist/BeforeRenderActivity-dyn", "auth-provider/js/dist/RenewTokenActivity-dyn"];

beforeRenderPaths = beforeRenderPaths.map(path => env === "development" ? `../${path}` : `./plugins/${beforeRenderPath}`);

module.exports = {
  //...
  entry: {
    a: { import: "./src/a.js", dependOn: "shared" },
    b: { import: "./src/b.js", dependOn: "shared" },
    c: { import: [ "./src/c.js", "./src/f.js"], dependOn: "shared"},
    'shared': beforeRenderPaths,
  },
  //...
  runtimeChunk: true
};

And then, make sure to import the shared modules in all the places like so -

import 'before-render/js/dist/BeforeRenderActivity-dyn';
import 'auth-provider/js/dist/RenewTokenActivity-dyn';

Let me know if I misunderstood something or missed something.

NOTE: This practice is frowned upon by webpack. Read this for more information and check this for understanding exactly why. I'm guessing that your use case is to do some sort of housekeeping stuff before loading anything, like authentication, checking active plan etc.

huangapple
  • 本文由 发表于 2023年8月10日 21:34:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76876247.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定