2017-05-25 20 views
0

随着CommonsChunkPlugin我现在有我的代码分成:的WebPack 2:厂商,共同和具体捆绑

vendors.js 
common.js 
page-1.js 
page-2-authenticated.js 
page-3-authenticated.js 

于是就page-1.html我加载以下脚本:

<script src="vendors.js" /> 
<script src="common.js" /> 
<script src="page-1.js" /> 

它工作正常并且page-1.js,page-2-authenticated.jspage-3-authenticated.js中的所有共享代码被捆绑到common.js中。

正如你所看到的,我的应用程序需要用户登录page-2-authenticated.htmlpage-3-authenticated.html。但是,page-2-authenticated.jspage-3-authenticated.js中的共享代码也捆绑到common.js中。 。但我不希望打扰谁没有登录的用户,当你登录的是仅用于代码

所以对于page-2-authenticated.html我想有

<script src="vendors.js" /> 
<script src="common.js" /> 
<script src="common-authenticated.js" /> // Shared code for authenticated users 
<script src="page-2-authenticated.js" /> 

但是,当我在common-authenticated.js中导出测试变量并将其导入page-2-authenticated.jspage-3-authenticated.js时,此共享代码仍然捆绑到common.js中。而common-authenticated.js是空的(只是一些webpackJsonp([12],[],[85]);)。

我有以下的WebPack 2配置:

entry: { 
    vendors: ['react'], 
    common: 'index.js', 
    'common-authenticated': 'common-authenticated.js', 
    'page-1': 'page-1.js', 
    'page-2-authenticated': 'page-2-authenticated.js', 
    'page-3-authenticated': 'page-3-authenticated.js' 
}, 
plugins: [ 
    new webpack.optimize.CommonsChunkPlugin({ 
    // The order of this array matters 
    names: ['common', 'vendors'], 
    minChunks: 2 
    }) 
] 

问题:如何绑定特定的代码为common-authenticated.js?有任何想法吗?

回答

0

我可以使用下面的配置来解决它:

entry: { 
    // Same as in topic start 
}, 

plugins: [ 
    /* 
    * Check the files used for pages on which you need to be logged in 
    * and bundle the shared code of these files in a chunk named 
    * 'common-authenticated' (its output will be in 'common-authenticated.js') 
    */ 
    new webpack.optimize.CommonsChunkPlugin({ 
    name: 'common-authenticated', 
    chunks: [ 
     'page-2-authenticated', 
     'page-3-authenticated' 
    ], 
    minChunks: 2 
    }), 

    /* 
    * Now check for shared code in the bundle defined above plus the files for 
    * pages on which you do not need to be logged in. Bundle this shared code into 
    * 'common.js' 
    */ 
    new webpack.optimize.CommonsChunkPlugin({ 
    name: 'common', 
    chunks: [ 
     'common-authenticated', // Name of the chunk defined above 
     'page-1' 
    ], 
    minChunks: 2 
    }), 

    /* 
    * I don't really now how this works. But it works :). 
    * It generates the 'vendors.js' 
    */ 
    new webpack.optimize.CommonsChunkPlugin({ 
    name: 'vendors', 
    chunks: ['common', 'vendors'], 
    minChunks: 2 
    }) 
] 

它给我我想要的东西。 page-1.html中的脚本加载保持不变(我不需要common-authenticated.js)。并且page-2-authenticated.html现在有:

<script src="vendors.js" /> 
<script src="common.js" /> 
<script src="common-authenticated.js" /> // Shared code for authenticated users 
<script src="page-2-authenticated.js" />