简体   繁体   English

如何在没有动态导入的情况下拆分 commons js?

[英]How to split commons js in next without dynamic imports?

I have a file in my project that has several export ASSET_NAME = require('/assets/myAsset.png') exports like this, I use it for some ui bits that I want to use url-loader on in order to base64 these asset images.我的项目中有一个文件,其中有几个export ASSET_NAME = require('/assets/myAsset.png')像这样导出,我将它用于一些 ui 位,我想在这些 ui 位上使用url-loader以便对这些资产进行 base64图片。

I then use this file in various pages of my project ie import { ASSET_NAME } from "./assets.js"然后我在项目的各个页面中使用这个文件,即import { ASSET_NAME } from "./assets.js"

After inspecting my built project I can see that all these base64 strings are located in my commons.js file.检查我构建的项目后,我可以看到所有这些 base64 字符串都位于我的commons.js文件中。 Ideally I'd want this file to be it's own something like assets.js so it can load in parallel with commons.js .理想情况下,我希望这个文件是它自己的,比如assets.js这样它就可以与commons.js并行加载。 After reading the doc's only method I saw to do this was via dynamic imports , however I don't want to await this file nor load it when user makes certain action, I just want it to be separate file loaded to my page in parallel / separate from commons,js在阅读了文档的唯一方法后,我看到这样做是通过动态导入,但是我不想等待这个文件,也不想在用户执行某些操作时加载它,我只想将它作为单独的文件并行加载到我的页面/与公地分开,js

You need to specify a new splitChunk in your next.config.js file.您需要在next.config.js文件中指定一个新的splitChunk

// next.config.js

module.exports = {
  webpack(config, options) {
    if (!options.isServer) {
      config.optimization.splitChunks.cacheGroups.assetsChunk = {
        chunks: 'all',
        enforce: true,
        minChunks: 1,
        name: 'assets-chunk',
        priority: 10,
        test: /[\\\/]path-to-your-asset[\\\/]/,
      };
    }
    return config;
  },
};

Just replace path-to-your-asset to the import path (or some of it as it is a regex).只需将path-to-your-asset替换为导入路径(或其中一些,因为它是正则表达式)。

For more info read splitChunks docs .有关更多信息,请阅读splitChunks 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM