webpack4.x學(xué)習(xí)之路
一矛纹、概念
本質(zhì)上萎庭,webpack是一個(gè)JavaScript應(yīng)用程序的靜態(tài)模塊打包工具霜医。其實(shí)就是把css、html驳规、js肴敛、image可配置性的打包工具,實(shí)現(xiàn)項(xiàng)目模塊化吗购。
二医男、核心概念
- 入口(entry): 以這個(gè)作為入口點(diǎn),來(lái)打包其所相關(guān)的模塊捻勉。
- 輸出(output): 輸出入口打包后的bundle
- 模塊(module):相關(guān)打包所需要的loader集合
- 插件(plugins):擴(kuò)展插件镀梭,可以引入相關(guān)的插件,來(lái)優(yōu)化和資源管理踱启,注入相關(guān)的環(huán)境變量
- 模式(mode):可根據(jù)不同的環(huán)境配置不同的參數(shù)报账,可選參數(shù)有development/production
三、webpack配置
1. 初始化項(xiàng)目以及安裝webpack依賴
npm init -y
npm i webpack webpack-cli -D
2. 配置 webpack.config.js
const path = require('path');
module.exports = {
entry: {
index: 'src/js/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[chunkHash:8].js'
}
};
在當(dāng)前目錄下輸入webpack --mode=production
打包
3. 使用模板html
html-webpack-plugin
可以指定template文件埠偿,然后將相關(guān)依賴的js透罢,引入到其頁(yè)面
安裝依賴:
npm i -D html-webpack-plugin
在webpack.config.js
中增加配置:
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
// ... other codes
plugins: [
new htmlwebpackplugin({
filename: 'index.html',
minify: {
removeAttributeQuotes: true
},
hash: true,
chunks: ['index'],
template: './src/index.html'
}),
]
}
4. 加載css文件
加載css文件要依靠相關(guān)的loader的轉(zhuǎn)化成js類型,所涉及到的loader有style-loader
, css-loader
冠蒋。
可通過(guò)以下命令來(lái)安裝依賴
npm i -D style-loader css-loader
在webpack.config.js中的配置如下:
module.exports = {
//other codes
module: {
rules: [
{
test: /\.css$/,
use: [{
loader: 'style-loader',
options: {
insertAt: 'top'
}
},
'css-loader'
],
//....
}
]
}
}
這里面牽扯到幾個(gè)概念:
- test: 匹配你需要轉(zhuǎn)換的文件擴(kuò)展名的正則表達(dá)式
- use: 所使用相關(guān)的loader的名稱
- include/exclude: 所必須處理的文件夾或不需要處理的文件夾
- query: 其他相關(guān)的配置選項(xiàng)
相關(guān)的css在js中引入才會(huì)打包到其相關(guān)的模塊中
5. 圖片加載
圖片加載相關(guān)的依賴有:
npm i -D file-loader url-loader
在webpack.config.js 中增加loader的配置如下:
module.exports = {
//other codes
module: {
rules: [
{
test: /\.(gif|jpg|png)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 500,
outputPath: 'images'
}
}
]
}
]
}
}
其實(shí)這只是打包c(diǎn)ss中的圖片羽圃,如果是頁(yè)面中用img標(biāo)簽引入的圖片,打包仍會(huì)報(bào)錯(cuò)抖剿,下面通過(guò)html-withimg-loader來(lái)打包
安裝依賴:
npm i html-withimg-loader -D
webpack.config.js
的配置
module: {
// other codes
rules: [{
test: /\.(html|htm)$/i,
use: ['html-withimg-loader']
}]
}
....未完待續(xù)