Webpack 4迁移CommonsChunkPlugin [英] Webpack 4 migration CommonsChunkPlugin

查看:147
本文介绍了Webpack 4迁移CommonsChunkPlugin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助将以下代码从webpack 3迁移到4。

I need help migrating the following code from webpack 3 to 4.

new webpack.optimize.CommonsChunkPlugin({
    minChunks: module => module.context && module.context.indexOf("node_modules") !== -1,
    name: "vendor",
    chunks: ["main"]
})

我有两个入口文件,只想要第一个的依赖项一个要包含在供应商块中。第二个条目的依赖关系应该都保留在自己的包中。

I have two entry files and want only the dependencies of the first one to be included in the vendor chunk. The dependencies of the second entry should all stay in its own bundle.

推荐答案

从webpack v4开始,CommonsChunkPlugin已被弃用。


我们已经弃用并删除了CommonsChunkPlugin,并用一组默认值和易于覆盖的API(
)替换了
optimization.splitChunks



webpack.optimize.CommonsChunkPlugin has been removed, 
please use config.optimization.splitChunks instead.






已弃用



您不再需要使用这些插件:


Deprecated

You no longer need to use these plugins:

DedupePlugin也已在v4中删除

NoEmitOnErrorsPlugin - > optimization.noEmitOnErrors(默认情况下在生产模式下启用)
ModuleConcatenationPlugin - > optimization.concatenateModules(默认情况下在prod模式下启用)
NamedModulesPlugin - > optimization.namedModules(默认情况下在开发模式下启用)

NoEmitOnErrorsPlugin -> optimization.noEmitOnErrors (on by default in production mode) ModuleConcatenationPlugin -> optimization.concatenateModules (on by default in prod mode) NamedModulesPlugin -> optimization.namedModules (on by default in dev mode)

建议用于webpack 4

Recommendations for webpack 4

使用 mini-css-extract-plugin 而不是文本提取物的插件
使用 webpack-bundle-analyzer 以图形方式分析您的捆绑输出。

Use mini-css-extract-plugin instead of text-extract-plugin. Use webpack-bundle-analyzer to analyze your bundled output in graphical way.

条目脚本是您应用程序的真正入门脚本,不要明确添加供应商文件到条目: webpack.config.js 中。
SPA应用程序有一个条目和多页面应用程序,如经典 ASP.NET MVC 应用程序有多个入口点。 Webpack将根据您的条目脚本构建一个依赖图,并为您的应用生成优化的捆绑包。

Entry scripts are real "Entry-Scripts" to your application, don't add vendor files explicitly to entry: in webpack.config.js. SPA apps have one entry and Multi-Page-Apps like classic ASP.NET MVC apps have multiple entry points. Webpack will build a dependenc graph out of your entry scripts and generate optimized bundles for your app.

如果您想从较旧的Webpack版本迁移,最好结帐迁移指南

If you want to migrate from an older webpack version, it's best to checkout the migration guide

树摇晃(死代码消除)仅在生产模式下启用。

Tree shaking (dead code elimination) is only enabled in production mode.

Webpack 4,捆绑资产的新方式

你必须从头脑中删除你的CommonsChunkPlugin

!!!同时webpack文档已更新,
a部分 SplitChunks 已添加!!!

!!! Meanwhile the webpack doc has been updated, a section SplitChunks was added !!!

遵循新的理念

默认情况下,Webpack 4现在会自动进行优化。它根据以下条件分析您的依赖图并创建最佳捆绑(输出):

Webpack 4 now by default does optimizations automatically. It analyzes your dependency graph and creates optimal bundles (output), based on the following conditions:



  1. 新块可以共享或模块来自node_modules文件夹

  2. 新块大于30kb(在min + gz之前)

  3. 最大并行请求数何时按需加载块< = 5

  4. 初始页面加载时的最大并行请求数< = 3

  1. New chunk can be shared OR modules are from the node_modules folder
  2. New chunk would be bigger than 30kb (before min+gz)
  3. Maximum number of parallel request when loading chunks on demand <= 5
  4. Maximum number of parallel request at initial page load <= 3


所有这一切都可以使用SplitChunksPlugin进行调整! (查看SplitChunksPlugin文档

All this can be tweaked using the SplitChunksPlugin! (see SplitChunksPlugin documentation)

有关如何使用新优化的更详细说明 .splitChunks API。

A more detailed explanation on how to use the new optimization.splitChunks API.



CommonsChunkPlugin已删除,因为它有很多问题:


  • 这可能导致下载的代码数量超过需要的数量。

  • 异步块上效率低下。

  • 很难使用。

  • 实施很难理解。

  • It can result in more code being downloaded than needed.
  • It’s inefficient on async chunks.
  • It’s difficult to use.
  • The implementation is difficult to understand.

SplitChunksPlugin还有一些很棒的属性:


  • 它永远不会下载不需要的模块(只要你不喜欢通过名称强制执行块合并)

  • 它也可以在异步块上高效工作

  • 默认情况下为异步块启用

  • 它使用多个供应商块来处理供应商拆分

  • 它更容易使用

  • 它不依赖于块图黑客

  • 大部分是自动的

  • It never downloads unneeded module (as long you don’t enforce chunk merging via name)
  • It works efficient on async chunks too
  • It’s on by default for async chunks
  • It handles vendor splitting with multiple vendor chunks
  • It’s easier to use
  • It doesn’t rely on chunk graph hacks
  • Mostly automatic

- > Source

关于您的问题,您希望将entry1和entry2的所有deps拆分为单独的包。

Regarding your issue, you want to split all deps of entry1 and entry2 into separate bundles.

      optimization: {
        splitChunks: {
          cacheGroups: {   
            "entry1-bundle": {
              test: /.../,   // <-- use the test property to specify which deps go here
              chunks: "all",
              name: "entry1-bundle",
 /** Ignore minimum size, minimum chunks and maximum requests and always create chunks for this cache group */
              enforce: true,
              priority: ..  // use the priority, to tell where a shared dep should go
            },
            "entry2-bundle": {
              test: /..../, // <-- use the test property to specify which deps go here
              chunks: "all",
              name: "entry2-bundle",
              enforce: true,
              priority: ..
            }
          }
        }
      },






如果您不添加优化:splitChunks条目,则默认设置如下

splitChunks: {
    chunks: "async",
    minSize: 30000,
    minChunks: 1,
    maxAsyncRequests: 5,
    maxInitialRequests: 3,
    automaticNameDelimiter: '~',
    name: true,
    cacheGroups: {
        vendors: {
            test: /[\\/]node_modules[\\/]/,
            priority: -10
        },
    default: {
            minChunks: 2,
            priority: -20,
            reuseExistingChunk: true
        }
    }
}

您可以将optimization.splitChunks.cacheGroups。默认设置为false以禁用默认缓存组,对于供应商缓存也是如此group!

You can set optimization.splitChunks.cacheGroups.default to false to disable the default cache group, same for vendors cache group!



SplitChunksOptions ,<$的最新接口实现c $ c> CachGroupOptions 和优化可以找到这里

下面的接口定义可能不是100%准确,但对于简单概述:

The interface definitions below may not be 100% accurate, but good for a simple overview:

SplitChunksOptions 界面

SplitChunksOptions interface

interface SplitChunksOptions {
    /** Select chunks for determining shared modules (defaults to \"async\", \"initial\" and \"all\" requires adding these chunks to the HTML) */
    chunks?: "initial" | "async" | "all" | ((chunk: compilation.Chunk) => boolean);
    /** Minimal size for the created chunk */
    minSize?: number;
    /** Minimum number of times a module has to be duplicated until it's considered for splitting */
    minChunks?: number;
    /** Maximum number of requests which are accepted for on-demand loading */
    maxAsyncRequests?: number;
    /** Maximum number of initial chunks which are accepted for an entry point */
    maxInitialRequests?: number;
    /** Give chunks created a name (chunks with equal name are merged) */
    name?: boolean | string | ((...args: any[]) => any);
    /** Assign modules to a cache group (modules from different cache groups are tried to keep in separate chunks) */
    cacheGroups?: false | string | ((...args: any[]) => any) | RegExp | { [key: string]: CacheGroupsOptions };
}

CacheGroupsOptions interface:

CacheGroupsOptions interface:

interface CacheGroupsOptions {
    /** Assign modules to a cache group */
    test?: ((...args: any[]) => boolean) | string | RegExp;
    /** Select chunks for determining cache group content (defaults to \"initial\", \"initial\" and \"all\" requires adding these chunks to the HTML) */
    chunks?: "initial" | "async" | "all" | ((chunk: compilation.Chunk) => boolean);
    /** Ignore minimum size, minimum chunks and maximum requests and always create chunks for this cache group */
    enforce?: boolean;
    /** Priority of this cache group */
    priority?: number;
    /** Minimal size for the created chunk */
    minSize?: number;
    /** Minimum number of times a module has to be duplicated until it's considered for splitting */
    minChunks?: number;
    /** Maximum number of requests which are accepted for on-demand loading */
    maxAsyncRequests?: number;
    /** Maximum number of initial chunks which are accepted for an entry point */
    maxInitialRequests?: number;
    /** Try to reuse existing chunk (with name) when it has matching modules */
    reuseExistingChunk?: boolean;
    /** Give chunks created a name (chunks with equal name are merged) */
    name?: boolean | string | ((...args: any[]) => any);
}

优化界面

Optimization Interface

interface Optimization {
    /**
     *  Modules are removed from chunks when they are already available in all parent chunk groups.
     *  This reduces asset size. Smaller assets also result in faster builds since less code generation has to be performed.
     */
    removeAvailableModules?: boolean;
    /** Empty chunks are removed. This reduces load in filesystem and results in faster builds. */
    removeEmptyChunks?: boolean;
    /** Equal chunks are merged. This results in less code generation and faster builds. */
    mergeDuplicateChunks?: boolean;
    /** Chunks which are subsets of other chunks are determined and flagged in a way that subsets don’t have to be loaded when the bigger chunk has been loaded. */
    flagIncludedChunks?: boolean;
    /** Give more often used ids smaller (shorter) values. */
    occurrenceOrder?: boolean;
    /** Determine exports for each module when possible. This information is used by other optimizations or code generation. I. e. to generate more efficient code for export * from. */
    providedExports?: boolean;
    /**
     *  Determine used exports for each module. This depends on optimization.providedExports. This information is used by other optimizations or code generation.
     *  I. e. exports are not generated for unused exports, export names are mangled to single char identifiers when all usages are compatible.
     *  DCE in minimizers will benefit from this and can remove unused exports.
     */
    usedExports?: boolean;
    /**
     *  Recognise the sideEffects flag in package.json or rules to eliminate modules. This depends on optimization.providedExports and optimization.usedExports.
     *  These dependencies have a cost, but eliminating modules has positive impact on performance because of less code generation. It depends on your codebase.
     *  Try it for possible performance wins.
     */
    sideEffects?: boolean;
    /** Tries to find segments of the module graph which can be safely concatenated into a single module. Depends on optimization.providedExports and optimization.usedExports. */
    concatenateModules?: boolean;
    /** Finds modules which are shared between chunk and splits them into separate chunks to reduce duplication or separate vendor modules from application modules. */
    splitChunks?: SplitChunksOptions | false;
    /** Create a separate chunk for the webpack runtime code and chunk hash maps. This chunk should be inlined into the HTML */
    runtimeChunk?: boolean | "single" | "multiple" | RuntimeChunkOptions;
    /** Avoid emitting assets when errors occur. */
    noEmitOnErrors?: boolean;
    /** Instead of numeric ids, give modules readable names for better debugging. */
    namedModules?: boolean;
    /** Instead of numeric ids, give chunks readable names for better debugging. */
    namedChunks?: boolean;
    /** Defines the process.env.NODE_ENV constant to a compile-time-constant value. This allows to remove development only code from code. */
    nodeEnv?: string | false;
    /** Use the minimizer (optimization.minimizer, by default uglify-js) to minimize output assets. */
    minimize?: boolean;
    /** Minimizer(s) to use for minimizing the output */
    minimizer?: Array<Plugin | Tapable.Plugin>;
    /** Generate records with relative paths to be able to move the context folder". */
    portableRecords?: boolean;
}
}

这篇关于Webpack 4迁移CommonsChunkPlugin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆