1. 程式人生 > >webpack 2.x 之 CommonsChunkPlugin

webpack 2.x 之 CommonsChunkPlugin

針對 antd-design 引入元件後文件很大,使用webpack 優化

由於 antd-desgin 設定按需載入,寫好的元件模組會很大,優化元件包大小有下列兩種方式

  1. 通過 webpack 設定 externals 從外部引入 antd.js 檔案(較方便、簡單);
  2. 通過 webpack 外掛 CommonsChunkPlugin 提取公共的部分(編譯過程有點不太容易控制);

解決過程:

  • 第一種方式,設定之後,從外部引入包後,部分 antd-design 的元件顯示有異常,Tabs 元件顯示異常

webpack.config.js

module.exports ={
    externals: {
        'react': 'React',
        'react-dom': 'ReactDOM',
        'echarts': 'echarts',
        'antd':'antd'
    }
}

xxx.jsx 元件檔案

const { Tabs } = antd
class xxx extends React.Component{
    render(){
        return (
            <div>
                <Tabs defaultActiveKey="2"
> <TabPane tab={<span><Icon type="bell" />報警池</span>} key="1"> {/* 表格 */} <WarnPoolTable height={this.props.height} /> </TabPane> <TabPane tab={<span><Icon type="compass"
/>本人負責</span>} key="2"> {/* 表格 */} <WarnPoolTable height={this.props.height} /> </TabPane> </Tabs> </div> ) } }

上述方式配置後,元件顯示有異常

  • 嘗試第二種方式 (CommonsChunkPlugin)

webpack.config.js配置

module.exports = {
    entry:{
        app:'./src/index.jsx',
        common_antd:['./src/components/xxx1','./src/components/xxx2','./src/components/xxx3'], // 正確打包的
    },
    plugins:{
        new webpack.optimize.CommonsChunkPlugin({
            name: "common_antd",
            filename: "common_antd.js",
            // chunks: [],  // 不設定,預設選擇所有的入口包提取公共部分
            // minChunks:2 // 最小公共模組的包
        }),
    }
}

webpack.config.js 打包出來的結果顯示 (開發環境下)

Hash: 641fcc71e2d7faf1576a
[1] Version: webpack 2.3.3
[1] Time: 135143ms
[1]                    Asset     Size  Chunks                    Chunk Names
[1]         Demo.97e49a77.js   103 kB       2  [emitted]         Demo
[1]                 u236.jpg    60 kB          [emitted]
[1]            blindfold.png    19 kB          [emitted]
[1]             greeting.png  22.7 kB          [emitted]
[1]   Navigation.8865c3be.js   115 kB       0  [emitted]         Navigation
[1]        Login.a5fa4bfb.js   117 kB       1  [emitted]         Login
[1]            userlogin.png  21.7 kB          [emitted]
[1] NotFoundPage.66335af2.js  2.29 kB       3  [emitted]         NotFoundPage
[1]          app.641fcc71.js   559 kB       4  [emitted]  [big]  app
[1]           common_antd.js  7.73 MB       5  [emitted]  [big]  common_antd
[1]         app.641fcc71.css  11.5 kB       4  [emitted]         app
[1] common_antd.641fcc71.css   240 kB       5  [emitted]         common_antd
[1]               index.html  2.24 kB          [emitted]

這是我打包出來的大小,生產環境common_antd.js 只有 2.5MB 大小,滿足我的要求

如果想更大化的減少開發環境下的打包時間,可以把上述兩種方式結合在一起,減少 webpack 熱載入打包時間長的問題(雖然 webpack 中已經使用了 devtool: 'eval') 減少打包時間,但還不夠快;