webpack+react+antd腳手架優化

圓兒圈圈發表於2019-03-04

在之前的文章中瞭解了webpack v4的特性,現在將知識用於實踐,對之前寫的一個react腳手架進行打包效能的優化。

優化類目

  • 樣式分離
  • 第三方資源分離
  • 區分開發環境
  • 熱更新
  • 提取公共程式碼

1. CSS分離

npm install extract-text-webpack-plugin -D
複製程式碼

webpack.config.js

將css、less、sass檔案單獨從打包檔案中分離

+ let cssExtract = new ExtractTextWebpackPlugin({
+    filename: 'css.css',
+    allChunks: true
+ });
+ let sassExtract = new ExtractTextWebpackPlugin('sass.css')
+ let lessExtract = new ExtractTextWebpackPlugin('less.css')
複製程式碼

在webpack.config.js中單獨新增規則,

  • test:匹配處理檔案的副檔名的正規表示式
  • include/exclude手動指定必須處理的資料夾或遮蔽不需要處理的資料夾
{
    test: /\.css$/,
    use: cssExtract.extract({
        fallback: "style-loader",
        use: ['css-loader?minimize','postcss-loader'],
        publicPath: "/dist"
    }),
    include:path.join(__dirname,'./src'),
    exclude:/node_modules/
},
{
    test: /\.scss$/,
    use: sassExtract.extract({
        fallback: "style-loader",
        use: ["css-loader?minimize","sass-loader"],
        publicPath: "/dist"
    }),
    include:path.join(__dirname,'./src'),
    exclude:/node_modules/
},
{
    test: /\.less$/,
    loader: lessExtract.extract({
        use: ["css-loader?minimize", "less-loader"]
    }),
    include:path.join(__dirname,'./src'),
    exclude:/node_modules/
},
複製程式碼

然後執行webpack命令時報錯

compilation.mainTemplate.applyPluginsWaterfall is not a function

Use Chunks.groupsIterable and filter by instanceof Entrypoint instead
複製程式碼

研究得出結論:webpack升級到v4然而響應的外掛沒有升級的原故。

解決方法:安裝指定版本的依賴

"html-webpack-plugin": "^3.0.4"
"extract-text-webpack-plugin": "^4.0.0-beta.0"
複製程式碼

resolve

指定extension之後可以不用在require或是import的時候加副檔名,會依次嘗試新增副檔名進行匹配

resolve: {
    //引入模組的時候,可以不用副檔名
    extensions: [".js", ".less", ".json"],
    alias: {//別名
        "bootstrap": "bootstrap/dist/css/bootstrap.css"
    }
}
複製程式碼

配置別名後,在主js裡引入bootstrap可以簡寫成

import 'bootstrap';
複製程式碼
npm install bootstrap@4.0.0-beta -D
npm install jquery -D
npm install popper.js -D


webpack.config.js

plugins: [
    ...
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
        Popper: ['popper.js', 'default'],
        ...
    })
]
複製程式碼

監聽檔案修改

webpack模式下使用,webpack-dev-server模式不用,可以將watch改為false

watchOptions: {
    ignored: /node_modules/,
    aggregateTimeout: 300, //監聽到變化發生後等300ms再去執行動作,防止檔案更新太快導致編譯頻率太高
    poll: 1000 //通過不停的詢問檔案是否改變來判斷檔案是否發生變化,預設每秒詢問1000次
}
複製程式碼

提取公共程式碼

    optimization: {
        splitChunks: {
            cacheGroups: {
                commons: {
                    chunks: "initial",
                    minChunks: 2,
                    maxInitialRequests: 5, // The default limit is too small to showcase the effect
                    minSize: 0 // This is example is too small to create commons chunks
                },
                vendor: {
                    test: /node_modules/,
                    chunks: "initial",
                    name: "vendor",
                    priority: 10,
                    enforce: true
                }
            }
        }
    }
複製程式碼

分離react react-dom ant公共程式碼

  • 方法一:externals

在頁面上引入第三方資源庫,然後使用externals防止將某些 import 的包(package)打包到 bundle 中,而是在執行時(runtime)再去從外部獲取這些擴充套件依賴(external dependencies)。

<script src="https://cdn.bootcss.com/react/16.4.0-alpha.0911da3/cjs/react.production.min.js"></script>
<script src="https://cdn.bootcss.com/react-dom/16.4.0-alpha.0911da3/cjs/react-dom-server.browser.production.min.js"></script>
複製程式碼
externals: { 'react': 'React', 'react-dom': 'ReactDOM', // 提出ant design的公共資源, }
複製程式碼
  • 方法二:DLL

DLL在上篇文章中寫過,但是打包後一直出現

webpack+react+antd腳手架優化
後來才發現是頁面上沒有引入資源。。。。(我一直以為會webpack自動生成在頁面上....)

在index.html檔案中引入

    <script src="./vendor/react.dll.js"></script>
複製程式碼

分離成功!上程式碼

webpack.base.js

var path = require('path');
var webpack = require('webpack');
var ExtractTextWebpackPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin')

let cssExtract = new ExtractTextWebpackPlugin({
    filename: 'css.css',
    allChunks: true
});
let sassExtract = new ExtractTextWebpackPlugin('sass.css')
let lessExtract = new ExtractTextWebpackPlugin('less.css')

module.exports = {
    entry:'./src/index.js',
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'bundle.[hash:8].js',
        publicPath: ''
    },
    resolve: {
        //引入模組的時候,可以不用副檔名
        extensions: [".js", ".less", ".json"],
        alias: {//別名
            "bootstrap": "bootstrap/dist/css/bootstrap.css"
        },
        modules: [path.resolve(__dirname, 'node_modules')]
    },
/*    externals: {
        'react': 'React',
        'react-dom': 'ReactDOM',
        // 提出ant design的公共資源
        //'antd': 'antd',
    },*/
    devtool: 'source-map',
    devServer: {
        contentBase:path.resolve(__dirname,'dist'),
        publicPath: '/',
        port: 8080,
        hot:true,
        compress:true,
        historyApiFallback: true,
        inline: true
    },
    watch: false, //只有在開啟監聽模式時,watchOptions才有意義
    watchOptions: {
        ignored: /node_modules/,
        aggregateTimeout: 300, //監聽到變化發生後等300ms再去執行動作,防止檔案更新太快導致編譯頻率太高
        poll: 1000 //通過不停的詢問檔案是否改變來判斷檔案是否發生變化,預設每秒詢問1000次
    },
    optimization: {
        splitChunks: {
            cacheGroups: {
                commons: {
                    chunks: "initial",
                    minChunks: 2,
                    maxInitialRequests: 5, // The default limit is too small to showcase the effect
                    minSize: 0 // This is example is too small to create commons chunks
                },
                vendor: {
                    test: /node_modules/,
                    chunks: "initial",
                    name: "vendor",
                    priority: 10,
                    enforce: true
                }
            }
        }
    },
    module: {
        rules:[
            {
                test: /\.js$/,
                use: {
                    loader:'babel-loader',
                    options: {
                        presets: ['env','es2015', 'react'],
                    }
                },
                include:path.join(__dirname,'./src'),
                exclude:/node_modules/
            },
            {
                test: /\.css$/,
                use: cssExtract.extract({
                    fallback: "style-loader",
                    use: ['css-loader?minimize','postcss-loader'],
                    publicPath: "/dist"
                }),
                include:path.join(__dirname,'./src'),
                exclude:/node_modules/
            },
            {
                test: /\.scss$/,
                use: sassExtract.extract({
                    fallback: "style-loader",
                    use: ["css-loader?minimize","sass-loader"],
                    publicPath: "/dist"
                }),
                include:path.join(__dirname,'./src'),
                exclude:/node_modules/
            },
            {
                test: /\.less$/,
                loader: lessExtract.extract({
                    use: ["css-loader?minimize", "less-loader"]
                }),
                include:path.join(__dirname,'./src'),
                exclude:/node_modules/
            },
            {
                test: /\.(html|htm)/,
                use: 'html-withimg-loader'
            },
            {
                test: /\.(png|jpg|gif|svg|bmp|eot|woff|woff2|ttf)/,
                use: {
                    loader:'url-loader',
                    options:{
                        limit: 5 * 1024,
                        //指定拷貝檔案的輸出目錄
                        outputPath: 'images/'
                    }
                }
            }
        ]
    },
    plugins: [
        //定義環境變數
        new webpack.DefinePlugin({
            __development__: JSON.stringify(process.env.NODE_ENV)
        }),
        new CleanWebpackPlugin(['dist']),
        cssExtract,
        lessExtract,
        sassExtract,
        new HtmlWebpackPlugin({
            title: 'React Biolerplate by YuanYuan',
            template: './src/index.html',
            filename: `index.html`,
            hash: true
        }),
        new webpack.DllReferencePlugin({
            manifest: path.join(__dirname, 'vendor', 'react.manifest.json')
        }),
        new CopyWebpackPlugin([{
            from: path.join(__dirname,'vendor'),//靜態資源目錄源地址
            to:'./vendor' //目標地址,相對於output的path目錄
        }]),
/*        new webpack.optimize.CommonsChunkPlugin({
            name: 'common' // 指定公共 bundle 的名稱。
    +     })*/
        new webpack.HotModuleReplacementPlugin(), // 熱替換外掛
        new webpack.NamedModulesPlugin() // 執行熱替換時列印模組名字
    ]
};
複製程式碼

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');//用來合併配置檔案
const base = require('./webpack.base');
let other = '';

//console.log(process.env.NODE_ENV )
if (process.env.NODE_ENV == 'development') {
    other = require('./webpack.dev.config');
} else {
    other = require('./webpack.prod.config');
}
//console.log(merge(base, other));

module.exports = merge(base, other);
複製程式碼

webpack.prod.config.js

const path = require('path');
const webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')

module.exports = {
    output: {
        filename: 'bundle.min.js',
    },
    plugins: [
        new UglifyJSPlugin({sourceMap: true})
    ]
}
複製程式碼

原腳手架地址

webpack+react+antd腳手架優化
優化後手架地址

webpack+react+antd腳手架優化

打包速度優化,打包檔案細化,改造成功~

覺得好玩就關注一下~歡迎大家收藏寫評論~~~

相關文章