Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何使用webpack里的CommonsChunkPlugin插件 #20

Open
songhlc opened this issue Oct 24, 2016 · 0 comments
Open

如何使用webpack里的CommonsChunkPlugin插件 #20

songhlc opened this issue Oct 24, 2016 · 0 comments

Comments

@songhlc
Copy link
Owner

songhlc commented Oct 24, 2016

如何使用webpack里的CommonsChunkPlugin插件

CommonsChunkPlugin用于将一个传统的js应用拆分成不同的模块,并在重用公共依赖的模块

为什么要使用CommonsChunkPlugin?

它非常适合用于开发一个由很多页面组成的应用(无论是传统的页面或者是页面路由)

1.单入口文件

在使用webpack时,通常会把所有的代码都打包到一个入口文件entry.js 之中。当项目规模比较小的时候并没有什么,但如果项目规模比较大里之后,这就意味着在不同页面会有一堆无用的代码被引用。

//不存在代码分割
entry.js
 - app
 - page1
 - page2 
 - jquery
 - underscore
 - moment

2.多页面文件

进行代码分隔之后在entry.js之中只需要引入启动工程所必须的代码,对于每一个页面则只引入页面需要的代码。

entry.js
 - app
 - jquery
 - underscore

page1.js
 - page1
 - jquery
 - moment

page2.js
 - page2
 - underscore

问题:jquery和underscore引用重复了

CommonsChunkPlugin的出现就是为了更高效的解决这些外部的依赖关系

3.优化后的结构

entry.js
 - app
 - jquery
 - underscore

page1.js
 - page1
 - moment

page2.js
 - page2

在这个示例中,juqery和underscore因为众多页面都有对它的依赖,所以移入了入口文件entry.js之中。

提取可重用依赖

在webpack中,通过给plugin添加一个webpack.optimize.CommonsChunkPlugin实例来实现,如下:

// webpack configuration
const webpack = require("webpack");
module.exports = {
  entry: {
    entry: './app.js'
  },
  output: {
    ...
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      // name of the entry chunk to scan for common (shared) dependencies
      // the common dependencies will be moved into this entry chunk
      name: 'entry',
      // indicate that we want to scan for common dependencies in
      // child (code split) chunks of the named entry chunk
      children: true,
      // minimum number of different chunks (entry or split) which a dependency
      // must be used by to deem it a common dependency
      minChunks: 2
    })
  ]
};

关于其他更多的CommonsChunkPlugin的配置请看
http://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin

ps:后续会更新vue-cli 创建的webpack模板的例子解析

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant