webpack打包时html-webpack-plugin不自动的引用CommonsChunkPlugin公共文件

webpack打包的时CommonsChunkPlugin抽出的公共js和css文件,html-webpack-plugin渲染出的html不自动的引用公共文件。

用wewbpack构建多页应用,每个页面单独一个入口js文件,用很多公共代码所以用了CommonsChunkPlugin对公共代码进行抽取,设定超过2次引用则抽取

但是当用了html-webpack-plugin渲染html时,如果某个文件被抽取成公共代码,则渲染后html则不会包含公共代码。

弄了一中午没有搞定,还望各位大神指点

源代码在这里:http://pan.baidu.com/s/1qXDVeAo

//webpack.config.js
var Path =require('path');
var Wp =require('webpack');
var ETWP =require('extract-text-webpack-plugin');
var HWP = require('html-webpack-plugin');
var eSCSS = new ETWP('css/[name].css');

module.exports ={
    entry :{
        indexApp: Path.resolve(__dirname ,'./src/js/index.js'),
        aboutApp: Path.resolve(__dirname ,'./src/js/about.js'),
    },
    output :{
        path :'./lib/',
        filename :'js/[name].js',
    },
    module :{
        loaders :[
            {
                test: /\.scss$/i, 
                loader: eSCSS.extract(['css','sass']),
            },
        ],
    },
    plugins :[
        new HWP({
            filename: './about.html',
            template: './src/tpl/about.html',
            chunks:["aboutApp","library.js"],
            xhtml: true,
            inject: true,
        }),
        new HWP({
            filename: './index.html',
            template: './src/tpl/index.html',
            chunks:["indexApp"],
            xhtml: true,
            inject: true,
        }),
        new Wp.optimize.CommonsChunkPlugin({
            name: 'library',
            minChunks:2,
        }),
    
};




阅读 8k
2 个回答

原因是因为你在html-webpack-plugin的参数里指定了chunks参数却又没有把CommonChunk包含在内。

把你的CommonChunk(在你的例子里叫library)加进chunks里就好了,比如例子里的chunks:["library", "aboutApp","library.js"]

你既然用到了CommonChunk的插件的话,那么在不管在哪个入口页面里都必须要把CommonChunk的包给带上,要不然会报错。因为其他的包会有对CommonChunk的依赖。

我觉得楼主可以通过:

    require.ensure([], function() {
        require('someChunks');
        //do something else
    })

这样可以:

  • 异步加载模块

  • 不需要一开始加载CommonChunk(如果你的入口文件确实不需要的话).

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题