獲取全套webpack 4.x教程愚铡,請訪問瓦力博客
在上一小節(jié)突勇,我們將開發(fā)環(huán)境和生產(chǎn)環(huán)境區(qū)分開來健芭。這一小節(jié)奸汇,我們來操作如何將樣式文件的代碼分割
施符。
- MiniCssExtractPlugin{:target="_blank"}
1.安裝
yarn add mini-css-extract-plugin
此插件將CSS提取到單獨的文件中。它為每個包含CSS的JS文件創(chuàng)建一個CSS文件擂找。它支持CSS和SourceMaps的按需加載戳吝。
它建立在新的webpack v4功能(模塊類型)之上,并且需要webpack 4才能工作贯涎。
注意:MiniCssExtractPlugin 目前不支持HMR support(熱重載)
2.提取css
bulid/plugins.js
const srcPath = require('./base/path');
const config = require('./base/config');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin'); //生成html文件
const { CleanWebpackPlugin } = require('clean-webpack-plugin'); //清除
+ const MiniCssExtractPlugin = require("mini-css-extract-plugin"); //css樣式提取
let plugins = [
new HtmlWebpackPlugin({
title: '瓦力博客',
template: srcPath.src + '/index.html' //以src/index.html為編譯模板
}),
+ new MiniCssExtractPlugin({
+ filename: config.NODE_ENV == 'development'?'[name.css]': `${srcPath.css}/[name].[hash].css`,
+ chunkFilename: config.NODE_ENV == 'development'?'[id].css': `${srcPath.css}/[id].[hash].css`
+ }), //css提取
new CleanWebpackPlugin(),
new webpack.HotModuleReplacementPlugin()
]
module.exports = plugins;
build/module.js
const srcPath = require('./base/path');
const config = require('./base/config');
+ const MiniCssExtractPlugin = require("mini-css-extract-plugin");
let _module = {
rules:[
{
test:/\.css$/,
use:[
+ config.NODE_ENV == 'development'?'style-loader': MiniCssExtractPlugin.loader,
{
loader:'css-loader',
options:{
importLoaders:1
}
},
'postcss-loader'
]
},
{
test:/\.scss$/,
use:[
+ config.NODE_ENV == 'development'?'style-loader': MiniCssExtractPlugin.loader,
{
loader:'css-loader',
options:{
importLoaders:2
}
},
'sass-loader',
'postcss-loader'
]
},
{
test: /\.less$/,
use: [
+ config.NODE_ENV == 'development'?'style-loader': MiniCssExtractPlugin.loader,
{
loader:'css-loader',
options:{
importLoaders:2
}
},
'less-loader',
'postcss-loader'
]
},
{
test:/\.(png|svg|jpeg|jpg|gif)$/,
use:[
{
loader:'file-loader',
options:{
name:'[name][sha512:hash:base64:7].[ext]', //[path] 上下文環(huán)境路徑
outputPath: srcPath.images, //輸出路徑
publicPath: config.NODE_ENV === 'development'?srcPath.images:srcPath.images //公共路徑
}
},
{
loader: 'image-webpack-loader',
options: {
bypassOnDebug: true, // webpack@1.x
disable: true, // webpack@2.x and newer
},
},
]
},
{
test: /\.html$/,
use:[
{
loader:'html-loader',
options:{
arrts:['img:src','img:data-src'],
+ minimize:config.NODE_ENV === 'development'? false:false //是否壓縮html
}
}
]
},
{
test: /(iconfont.svg)|\.(woff|woff2|eot|ttf|otf)$/,
use:[
{
loader:'file-loader',
options:{
name:'[name].[ext]', //[path] 上下文環(huán)境路徑
outputPath: srcPath.iconfont, //輸出路徑
publicPath: config.NODE_ENV === 'development'? srcPath.iconfont: srcPath.iconfont, //公共路徑
}
}
]
},
{
test: /\.js$/,
exclude: /(node_modules|bower_components|lib)/,
loader: 'babel-loader'
}
]
}
module.exports = _module;
build/base/config.js
let _mode = process.argv[process.argv.length - 1];
let env = _mode.replace(/--mode=(.+)/g,"$1");
let config = {
NODE_ENV: env == 'development'?'development':'production', //development 開發(fā) production 線上
+ publicPath: env == 'development'?'./':'./',
apiUrl:'http://www.waliblog.com',
port: 9999
}
module.exports = config;
package.json
{
"name": "webpack",
"version": "1.0.0",
"description": "webpack測試",
"sideEffects": [
"*.css",
+ "*.less",
+ "*.scss"
],
"main": "index.js",
"author": "wali",
"private": true,
"license": "MIT",
"scripts": {
"dev": "npx webpack-dev-server --colors --mode=development",
"prod": "npx webpack --colors --mode=production",
"build": "npx webpack --colors --mode=development",
"analyse": "npx webpack --profile --json> stats.json --colors --mode=development"
},
"dependencies": {
"@babel/core": "^7.4.5",
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/plugin-transform-runtime": "^7.4.4",
"@babel/polyfill": "^7.4.4",
"@babel/preset-env": "^7.4.5",
"@babel/runtime": "^7.4.5",
"@babel/runtime-corejs2": "^7.4.5",
"autoprefixer": "^9.5.1",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^2.1.1",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^3.0.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"image-webpack-loader": "^4.6.0",
"json5-loader": "^2.0.0",
"less": "^3.9.0",
"less-loader": "^5.0.0",
"loadsh": "^0.0.4",
"lodash": "^4.17.11",
"mini-css-extract-plugin": "^0.7.0",
"node-sass": "^4.12.0",
"postcss-loader": "^3.0.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.32.0",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.4.1"
},
"devDependencies": {
"webpack-bundle-analyzer": "^3.3.2"
}
}
index.js
import './assets/css/index.css';
assets/css/index.css
h1{
color: blue;
}
運行webpack
yarn run prod
打開dist/index.html
,看到/assets/css/index.css
文件樣式生效了
<!--dist/index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title</title>
<link href="./assets/css/main.2df4cfd436df0ec42c4d.css" rel="stylesheet"></head>
<body>
<h1>歡迎來到瓦力博客</h1>
<span class="iconfont wali-icon-fuzhi"></span>
<img src="assets/images/wali_logo2BQg9e7.png" alt="">
<script type="text/javascript" src="./main.2df4cfd436df0ec42c4d.js"></script></body>
</html>
從index.html
文件中可以看到css文件被提取出來听哭,并且被引用。
3.提取sass
上面配置已經(jīng)寫了塘雳,在plugins.js
和module.js
文件中配置了陆盘,這里就簡單的驗證一下
修改index.js
import './assets/sass/index.scss';
assets/sass/index.scss
body{
h1{
transform: translate(100px, 100px);
}
}
運行webpack
yarn run prod
打開dist/index.html
發(fā)現(xiàn)歡迎來到瓦力博客
幾個字發(fā)生偏移,說明/assets/sass/index.scss
樣式已經(jīng)生效
4.提取less
上面配置已經(jīng)寫了败明,在plugins.js
和module.js
文件中配置了隘马,這里就簡單的驗證一下
修改index.js
import './assets/less/index.less';
assets/less/index.less
body{
h1{
transform: rotate(90deg);
background: red;
text-align: center;
}
}
運行webpack
yarn run prod
打開dist/index.html
發(fā)現(xiàn)歡迎來到瓦力博客
幾個字旋轉(zhuǎn)90度,背景變紅肩刃,字體居中祟霍,說明/assets/less/index.less
樣式已經(jīng)生效
5.總結(jié)
測試這小節(jié)其實遇到幾個問題杏头,小菜寫出來:
調(diào)試
這小節(jié)的測試命令都變成yarn run prod
,是測試生產(chǎn)環(huán)境下webpack配置沸呐,生產(chǎn)環(huán)境下css
,less
,scss
都會被壓縮醇王,去注釋,index.html
文件也會被壓縮崭添,去注釋寓娩,還要添加域名。這樣一來從生成的文件方面就不容易看出webpack到底是否配置正確呼渣。所以小菜將config.js
中修改
+ publicPath: env == 'development'?'./':'./',
就是生成后index.html文件能直接在本地打開而不報錯棘伴。
build/module.js
修改
+ minimize:config.NODE_ENV === 'development'? false:false //是否壓縮html
生成后index.html文件不要被壓縮,還保留樹形結(jié)構(gòu)屁置,便于查找
less和scss文件樣式不起作用
小菜起初測試css
文件焊夸,發(fā)現(xiàn)打包后css樣式被提取出來,樣式也生效了蓝角,但是換成
import './assets/less/index.less';
//或
import './assets/sass/index.scss';
時阱穗,在運行打包命令時,樣式?jīng)]有被提取出來使鹅。后來經(jīng)過認(rèn)真分析揪阶,發(fā)現(xiàn)/webpack/2019/05/24/webpack-10.html一節(jié)中配置了Tree Shaking
。Tree shaking
作用就是當(dāng)我在index.js
文件中使用import './assets/less/index.less'
寫法時患朱,會檢測在js文件中是否使用了引入來的less
鲁僚,很明顯在index.js
文件中沒有使用,只是單純的引入裁厅,所以Tree shaking
就會自動幫我們過濾掉這行代碼冰沙,就導(dǎo)致最終生成的js文件中沒有樣式,也就提取不出來樣式了姐直。
看了上面的解釋倦淀,有的小伙伴可能會問import './assets/css/index.css'
也在index.js
文件中只引用沒有使用,為什么css文件中的樣式就能夠生效呢声畏?原因還是在/webpack/2019/05/24/webpack-10.html一節(jié)中撞叽,小菜在package.json
中配置了css,沒有配置less
,scss
插龄。
"sideEffects": [
"*.css",
+ "*.less",
+ "*.scss"
],
當(dāng)我們配置*.css
,*.less
,*.scss
后愿棋,在Tree shaking
時,webpack就會知道忽略css
,less
,scss
所有文件均牢,即使在js文件中css
,less
,scss
只引用沒有使用糠雨,也不要刪除這行代碼。
6.代碼回滾
build/module.js
- minimize:config.NODE_ENV === 'development'? false:false //是否壓縮html
+ minimize:config.NODE_ENV === 'development'? false:true //是否壓縮html
build/base/config.js
let _mode = process.argv[process.argv.length - 1];
let env = _mode.replace(/--mode=(.+)/g,"$1");
let config = {
NODE_ENV: env == 'development'?'development':'production', //development 開發(fā) production 線上
- publicPath: env == 'development'?'./':'./',
+ publicPath: env == 'development'?'./':'http://www.waliblog.com/',
apiUrl:'http://www.waliblog.com',
port: 9999
}
module.exports = config;