最近在学习webpack的一些配置,学习的指望就是经过能够经过webpack给html文件中引用的资源例如css、js、img文件加上版本号,避免因为浏览器的缓存形成线上请求的资源依旧是旧版本的东西。javascript
首先新建一个webpack的项目(默认你们已经安装node的了)css
npm init
复制代码
项目中安装webpackhtml
npm webpack --save-dev
npm webpack-cli --save-dev
复制代码
而后就能够开心的写代码了java
在项目的根目录下,新建一个webpack.config.js文件,node
npm install --save-dev html-webpack-plugin mini-css-extract-plugin
clean-webpack-plugin
复制代码
当使用 webpack打包时,建立一个 html 文件,并把 webpack 打包后的静态文件自动插入到这个 html 文件当中,而且可使用自定义的模版,例如html、pug、ejs,还可配置hash值等一些配置。 具体可配置的参数仍是不少的,像title、meta等等,可参考webpack官网jquery
webpack 4.0之后,把css样式从js文件中提取到单独的css文件中; 这在项目中的使用场景是把css文件在js文件中import进来,打包的时候该插件会识别到这个css文件,经过配置的路径参数生成一个打包后的css文件。webpack
是用于在下一次打包时清除以前打包的文件,可参考webpack官网git
Babel
把用最新标准编写的 JavaScript
代码向下编译成能够在今天随处可用的版本github
它默认处理html中的<img src="image.png">
为require("./image.png")
,同时须要在你的配置中指定image
文件的加载器,好比:url-loader
或者file-loader
web
用于解决项目中的图片打包问题,把图片资源打包进打包文件中,可修改对应的文件名和路径,url-loader比file-loader多一个可配置的limit属性,经过此参数,可配置若图片大小大于此参数,则用文件资源,小于此参数则用base64格式展现图片;
打包css文件并插入到html文件中;
单页面打包webpack.config.js的配置
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const {
CleanWebpackPlugin
} = require('clean-webpack-plugin');
const path = require("path");
module.exports = {
mode: "development",
entry: path.resolve(__dirname, './src/index.js'),
output: {
filename: "bundle.js",
path: path.resolve(__dirname, 'build'),
// libraryTarget: 'umd'
},
module: {
rules: [{
test: /\.html$/,
use: [{
loader: "html-loader",
options: {
attrs: ['img:src', 'link:href']
}
}]
},
{
test: /\.js$/,
use: {
loader: "babel-loader"
},
include: path.resolve(__dirname, '/src'),
exclude: /node_modules/,
},
{
test: /\.(jpg|png|gif|bmp|jpeg)$/,
use: [{
// loader: 'file-loader',
loader: 'url-loader',
options: {
limit: 8192,
// name: '[name].[ext]',
name: '[name]-[hash:8].[ext]',
outputPath: 'images/',
}
}]
},
{
test: /\.pug$/,
use: {
loader: 'pug-loader'
}
},
{
test: /\.css$/,
use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader']
},
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
hash: true,
template: "src/index.html",
// template: "src/index.pug",
filename: "bundle.html",
}),
new MiniCssExtractPlugin({
filename: "bundle.css",
chunkFilename: "index.css"
}),
],
}
复制代码
在plugin中,有多个html-webpack-plugin插件的使用,可生成对应的打包后多个html文件
多页面打包webpack.config.js的配置
const getPath = require('./getPath')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const {
CleanWebpackPlugin
} = require('clean-webpack-plugin');
const path = require("path");
module.exports = {
mode: "development",
entry: {
main: './src/main/main.js',
side: './src/side/side.js',
// ...getPath.jsPathList,
},
output: {
path: path.resolve(__dirname, 'build'),
filename: 'js/[name].js',
publicPath: '../',
},
module: {
rules: [{
test: /\.html$/,
use: [{
loader: "html-loader",
options: {
attrs: ['img:src', 'link:href']
}
}, ]
},
{
test: /\.js$/,
use: [{
loader: "babel-loader",
options: {
presets: ['es2015']
}
}],
include: path.resolve(__dirname, '/src'),
exclude: /node_modules/,
},
{
test: /\.(jpg|png|gif|bmp|jpeg)$/,
use: [{
// loader: 'file-loader',
loader: 'url-loader',
options: {
limit: 8192,
name: '[name]-[hash:8].[ext]',
outputPath: './images', //指定放置目标文件的文件系统路径
publicPath: '../images',//指定目标文件的自定义公共路径
}
}]
},
{
test: /\.pug$/,
use: {
loader: 'pug-loader'
}
},
{
test: /\.css$/,
use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader']
},
]
},
plugins: [
new CleanWebpackPlugin(),
//输出html文件1
new HtmlWebpackPlugin({
hash: true,
template: "./src/main/main.html", //本地html文件模板的地址
filename: "html/main.html",
chunks: ['main'],
}),
new HtmlWebpackPlugin({
hash: true,
template: "./src/side/side.html",
filename: "html/side.html",
chunks: ['side'],
}),
// ...getPath.htmlPathList,
new MiniCssExtractPlugin({
filename: "css/[name].css",
chunkFilename: "./src/[name]/[name].css"
}),
]
}
复制代码
固然也能够经过函数获取全部须要打包的文件的路径,动态在webpack的配置文件中插入
const glob = require("glob");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
/** * * @param {string} globPath 文件的路径 * @returns entries */
function getPath(globPath) {
let files = glob.sync(globPath);
let entries = {},
entry, dirname, basename, extname;
files.forEach(item => {
entry = item;
dirname = path.dirname(entry); //当前目录
extname = path.extname(entry); //后缀
basename = path.basename(entry, extname); //文件名
//文件路径
if (extname === '.html') {
entries[basename] = entry;
} else if (extname === '.js') {
entries[basename] = entry;
}
});
return entries;
}
const jsPath = getPath('./src/*/*.js');
const htmlPath = getPath('./src/*/*.html');
const jsPathList = {};
const htmlPathList = [];
console.log("jsPath", jsPath)
Object.keys(jsPath).forEach((item) => {
jsPathList[item] = path.resolve(__dirname, jsPath[item])
})
Object.keys(htmlPath).forEach((item) => {
htmlPathList.push(new HtmlWebpackPlugin({
hash: true,
template: htmlPath[item],
filename: `html/${item}.html`,
chunks: [item],
// chunks: [item, 'jquery'],
}))
})
// console.log("htmlPathList", htmlPathList)
module.exports = {
jsPathList,
htmlPathList
}
复制代码
通过打包以后,某个文件夹下的html、css、jpg文件,会被分别打包放进build文件夹下的html文件夹、css文件夹和images文件夹,而且在html文件中引用的其余资源文件也加上了hash值做为版本号。
坑:
刚开始的时候url-loader和file-loader都是安装最新版本的,致使打包后图片的路径变成了
<img src="[object Module]"/>
因此此项目用的"url-loader": "^2.1.0"
,"file-loader": "^4.2.0"