溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

webpack+react+antd腳手架如何優(yōu)化

發(fā)布時間:2021-08-13 08:52:41 來源:億速云 閱讀:91 作者:小新 欄目:web開發(fā)

這篇文章主要介紹了webpack+react+antd腳手架如何優(yōu)化,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

優(yōu)化類目

  1. 樣式分離

  2. 第三方資源分離

  3. 區(qū)分開發(fā)環(huán)境

  4. 熱更新

  5. 提取公共代碼

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中單獨添加規(guī)則,

  1. test:匹配處理文件的擴展名的正則表達(dá)式

  2. 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

研究得出結(jié)論:webpack升級到v4然而響應(yīng)的插件沒有升級的原故。

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

"html-webpack-plugin": "^3.0.4"
"extract-text-webpack-plugin": "^4.0.0-beta.0"

resolve

指定extension之后可以不用在require或是import的時候加文件擴展名,會依次嘗試添加擴展名進(jìn)行匹配

resolve: {
 //引入模塊的時候,可以不用擴展名
 extensions: [".js", ".less", ".json"],
 alias: {//別名
 "bootstrap": "bootstrap/dist/css/bootstrap.css"
 }
}

監(jiān)聽文件修改

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

watchOptions: {
 ignored: /node_modules/,
 aggregateTimeout: 300, //監(jiān)聽到變化發(fā)生后等300ms再去執(zhí)行動作,防止文件更新太快導(dǎo)致編譯頻率太高
 poll: 1000 //通過不停的詢問文件是否改變來判斷文件是否發(fā)生變化,默認(rèn)每秒詢問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在上篇文章中寫過,但是打包后一直出現(xiàn)

webpack+react+antd腳手架如何優(yōu)化

后來才發(fā)現(xiàn)是頁面上沒有引入資源。。。。(我一直以為會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, //只有在開啟監(jiān)聽模式時,watchOptions才有意義
 watchOptions: {
 ignored: /node_modules/,
 aggregateTimeout: 300, //監(jiān)聽到變化發(fā)生后等300ms再去執(zhí)行動作,防止文件更新太快導(dǎo)致編譯頻率太高
 poll: 1000 //通過不停的詢問文件是否改變來判斷文件是否發(fā)生變化,默認(rèn)每秒詢問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: [
 //定義環(huán)境變量
 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'),//靜態(tài)資源目錄源地址
 to:'./vendor' //目標(biāo)地址,相對于output的path目錄
 }]),
/* new webpack.optimize.CommonsChunkPlugin({
 name: 'common' // 指定公共 bundle 的名稱。
 + })*/
 new webpack.HotModuleReplacementPlugin(), // 熱替換插件
 new webpack.NamedModulesPlugin() // 執(zhí)行熱替換時打印模塊名字
 ]
};

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腳手架如何優(yōu)化

優(yōu)化后手架地址

webpack+react+antd腳手架如何優(yōu)化

打包速度優(yōu)化,打包文件細(xì)化,改造成功~

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“webpack+react+antd腳手架如何優(yōu)化”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI