2017-05-25 16 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" />