首先将npm更改成cnpm,由于国内的npm有时下载速度很慢,能够安装cnpm,从国内淘宝镜像下载,执行如下命令:javascript
npm install -g cnpm --registry=https://registry.npm.taobao.org
复制代码
之后npm直接替换成cnpm使用。css
找个喜欢的目录,执行如下命令:html
mkdir webpack-demo
cd webpack-demo
npm init -y
npm install webpack webpack-cli --save-dev
复制代码
※注:本文代码区域每行开头的 “+”表示新增,“-或者D”表示删除,“M”表示修改,“...”表示省略。 dist为最终编译出来的生产环境代码,src为开发环境代码。java
/- webpack-demo
|- package.json
+ |- /dist
+ |- index.html
+ |- /src
+ |- index.js
复制代码
调整 package.json 文件,以便确保咱们安装包是私有的(private),而且移除 main 入口。这能够防止意外发布你的代码。 同时加入script命令,让执行npx webpack 等同于执行npm run build。node
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
+ "private": true,
- "main": "index.js",
"scripts": {
- "test": "echo \"Error: no test specified\" && exit 1",
+ "build": "webpack --mode production",
+ "dev": "webpack --mode development"
},
...
复制代码
编写dist/index.html,注意引入bundle.js(打包时会自动生成bundle.js)jquery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webpack Demo</title>
<script src="bundle.js"></script>
</head>
<body>
</body>
</html>
复制代码
编写src/index.js,随便写点。webpack
document.write('hello world');
复制代码
项目根目录建立webpack.config.js,用来配置webpack。git
|- package.json
|- /dist
|- index.html
|- /src
|- index.js
+ |- webpack.config.js
复制代码
编写webpack.config.js:github
const path = require('path');
module.exports = {
// 入口js路径
entry: './src/index.js',
// 编译输出的js及路径
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
复制代码
执行npm run build,生成的dist以下:web
|- /dist
|- index.html
+ |- bundle.js
复制代码
浏览器运行index.html,显示“hello world”。 以上是最原始的方式,须要在dist配置html,这样并不科学。咱们须要实现的是在src里开发,而后所有生成到dist中。请继续后面的章节。
安装clean-webpack-plugin,设置代码见2.3
npm install clean-webpack-plugin --save-dev
复制代码
安装html-webpack-plugin,设置代码见2.3
npm install html-webpack-plugin --save-dev
复制代码
构建目录以下
|- package.json
|- webpack.config.js
|- /dist
|- /src
|- /html
|- index.html
|- login.html
|- /js
|- index.js
|- login.js
复制代码
从新编写webpack.config.js
const path = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
// 入口js路径
entry: {
index: './src/js/index.js',
login: './src/js/login.js'
},
plugins: [
// 自动清空dist目录
new CleanWebpackPlugin(),
// 设置html模板生成路径
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/html/index.html',
chunks: ['index']
}),
new HtmlWebpackPlugin({
filename: 'login.html',
template: './src/html/login.html',
chunks: ['login']
}),
],
// 编译输出配置
output: {
// js生成到dist/js,[name]表示保留原js文件名
filename: 'js/[name].js',
// 输出路径为dist
path: path.resolve(__dirname, 'dist')
}
};
复制代码
如今执行npm run build,生成dist以下:
|- /dist
|- index.html
|- login.html
|- /js
|- index.js
|- login.js
复制代码
查看html代码,发现对应的js已经被引入了。
如今咱们搭建一个基于nodejs的服务器,让代码运行在开发环境,而且实如今修改代码时不用刷新便可自动热更新页面。
自动监测代码变化并实时刷新浏览器
npm install webpack-dev-server --save-dev
复制代码
修改package.json:
"scripts": {
"build": "webpack --mode production",
- "dev": "webpack --mode development"
+ "serve": "webpack-dev-server --open --mode development"
},
复制代码
修改webpack.config.js:
module.exports = {
entry: {...},
+ // 动态监测并实时更新页面
+ devServer: {
+ contentBase: './dist',
+ // 默认8080,可不写
+ port: 8080,
+ // 热更新,无需刷新
+ hot: true
+ },
plugins: [...],
...
};
复制代码
执行npm run serve,会在本地启动一个nodejs的web服务,浏览器会自动打开http://localhost:8080/。 经过http://localhost:8080/login.html能够访问login页面。 这时修改src下的js或者html文件,页面会自动更新。
module.exports = {
...
devServer: {...},
+ // 方便追踪源代码错误
+ devtool: 'source-map',
plugins: [...],
..
};
复制代码
webpack.config.js包含了生产环境和开发环境的配置,分离后,有利于代码的维护。
|- package.json
- |- webpack.config.js
+ |- webpack.common.js
+ |- webpack.dev.js
+ |- webpack.prod.js
|- /dist
|- /src
复制代码
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: {...},
plugins: [...],
output: {...}
};
复制代码
webpack.dev.js保留开发环境配置的代码
const merge = require('webpack-merge');
const common = require('./webpack.common');
module.exports = merge(common, {
// 动态监测并实时更新页面
devServer: {
contentBase: './dist',
// 默认端口8080,可不填
port: 8080,
// 热更新,无需刷新
hot: true
}
});
复制代码
webpack.prod.js保留生产环境配置的代码
const merge = require('webpack-merge');
const common = require('./webpack.common');
module.exports = merge(common, {
// 方便追踪源代码错误
//(若是不须要3.2小节的追踪功能,能够注释掉下行代码)
devtool: 'source-map'
});
复制代码
修改package.json:
"scripts": {
M "build": "webpack --config webpack.prod.js --mode production",
M "serve": "webpack-dev-server --open --config webpack.dev.js --mode development"
},
复制代码
本节以jQuery为例,讲解如何引入公用JS库。若是使用AngularJS、React或者Vue,建议使用官方的CLI工具。
安装jQuery:
npm install jquery --save
复制代码
jQuery是每一个页面都要用的,在每一个页面import太过于繁琐,修改webpack.common.js进行全局配置:
...
+ const webpack = require('webpack');
module.exports = {
...
plugins: [
+ new webpack.ProvidePlugin({
+ $: 'jquery',
+ jQuery: 'jquery'
+ }),
new CleanWebpackPlugin(),
...
复制代码
修改src/html/index.html,加入div,用于测试:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webpack Demo</title>
</head>
<body>
<div id="app">
<div id="info"></div>
</div>
</body>
</html>
复制代码
修改src/js/index.js:
$('#info').text('jQuery正常使用');
复制代码
执行npm run build,生成dist以下:
|- /dist
|- index.html
|- login.html
|- /js
|- index.js <--jQuery代码已集成到这里
|- login.js
复制代码
使用webpack的splitChunks来实现单独打包。
plugins: [
...
// 设置html模板生成路径
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/html/index.html',
M chunks: ['jquery', 'index']
}),
new HtmlWebpackPlugin({
filename: 'login.html',
template: './src/html/login.html',
M chunks: ['jquery', 'login']
}),
],
+ optimization: {
+ splitChunks: {
+ cacheGroups: {
+ commons: {
+ test: /jquery/,
+ name: 'jquery',
+ chunks: 'all'
+ }
+ }
+ }
+ },
// 编译输出配置
output: {...}
复制代码
执行npm run build,页面运行正常,生成dist以下:
|- /dist
|- index.html
|- login.html
|- /js
|- index.js
|- login.js
+ |- jquery.js <--jQuery已独立出来
复制代码
若是要兼容IE8等低版本浏览器,在开发过程当中使用ES6等高版本js语法,会导低版本浏览器没法运行。另外,jQuery只能使用1.x,要安装低版本jQuery。(若是不须要兼容IE8,请直接跳过本章节)
npm install jquery-1x --save
复制代码
修改webpack.common.js:
...
plugins: [
new webpack.ProvidePlugin({
M $: 'jquery-1x',
M jQuery: 'jquery-1x'
}),
...
复制代码
如今build出来的代码,IE8会在e.default代码处报错“缺乏标识符”。须要安装uglifyjs-webpack-plugin。
npm install uglifyjs-webpack-plugin --save-dev
复制代码
修改webpack.common.js
...
+ const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
...
optimization: {
splitChunks: { ... },
+ minimizer: [
+ new UglifyJsPlugin({
+ uglifyOptions: {
+ ie8: true
+ }
+ })
+ ]
},
复制代码
若是使用ES6语法,例如箭头函数,build会报错不经过。要把ES6转为ES5,须要安装如下插件(较多):
npm install babel-loader @babel/core @babel/preset-env --save-dev
npm install @babel/plugin-transform-runtime @babel/plugin-transform-modules-commonjs --save-dev
npm install @babel/runtime --save
复制代码
修改webpack.common.js,这里代码的做用是,在编译时把js文件中ES6转成ES5:
optimization: {...},
+ module: {
+ rules: [
+ {
+ test: /\.js$/,
+ exclude: /(node_modules|bower_components)/,
+ use: {
+ loader: 'babel-loader',
+ options: {
+ presets: ['@babel/preset-env'],
+ plugins: [
+ '@babel/plugin-transform-runtime',
+ '@babel/plugin-transform-modules-commonjs'
+ ]
+ }
+ }
+ }
+ ]
+ },
// 编译输出配置
output: {...}
复制代码
如今执行npm run build,编译经过。可是IE8下报错“对象不支持bind属性方法”,这是由于IE8不支持ES5,还须要引入es5-shim和es5-sham(见下节)。
尝试了不少网上的方法,都没有尝试成功,最后干脆用直接引用的方法来解决。
|- /src
|- /css
(略)
|- /html
|- index.html
|- login.html
|- /js
(略)
|- /static
|- /js
|- es5-shim.min.js
|- es5-sham.min.js
复制代码
而后,在src/html/index.html和src/html/login.html的里直接引入
<head>
<meta charset="UTF-8">
<title>>Webpack Demo</title>
+ <script type="text/javascript" src="static/js/es5-shim.min.js"></script>
</head>
复制代码
...
+ const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
...
plugins: [
...
new HtmlWebpackPlugin({
filename: 'login.html',
template: './src/html/login.html',
chunks: ['jquery', 'login']
}),
+ new CopyWebpackPlugin([
+ { from: './src/static', to: 'static' }
+ ])
复制代码
执行npm run build,在IE8下能够愉快的运行啦。
本节以Stylus为例,若是使用Sass/Less,能够参考本方法。混用CSS是为了同时掌握CSS使用方法。 *安装相关依赖包:
npm install style-loader css-loader --save-dev
npm install stylus-loader stylus --save-dev
复制代码
如今src目录以下:
|- /src
+ |- /css
+ |- /common
+ |- common.css
+ |- frame.css (这个文件@import common.css和reset.css)
+ |- reset.css
+ |- /pages
+ |- index.styl
+ |- login.styl
|- /html
|- index.html
|- login.html
|- /js
(略)
复制代码
css及styl内的样式代码,请自行补充,这里再也不展现了。
import '../css/common/frame.css';
import '../css/pages/index.styl';
login.js中引入样式:
import '../css/common/frame.css';
import '../css/pages/login.styl';
复制代码
module.exports = {
...
module: {
rules: [
+ {
+ test: /\.css$/,
+ use: [
+ 'style-loader',
+ 'css-loader'
+ ]
+ },
+ {
+ test: /\.styl$/,
+ use: [
+ 'style-loader',
+ 'css-loader',
+ 'stylus-loader'
+ ]
+ }
...
复制代码
执行build后,样式代码会直接打包插入到html文件中。
如今咱们想把样式经过link方式引入。
npm install mini-css-extract-plugin --save-dev
复制代码
而后修改webpack.common.js
···
+ const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
plugins: [
...
+ new MiniCssExtractPlugin({
+ filename: 'css/[name].css'
+ }),
new CopyWebpackPlugin([
{ from: './src/static', to: 'static' }
])
],
module: {
rules: [
{
test: /\.css$/,
use: [
+ // 将原来的style-loader替换
M MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test: /\.styl$/,
use: [
+ // 将原来的style-loader替换
M MiniCssExtractPlugin.loader,
'css-loader',
'stylus-loader'
]
}
···
复制代码
执行npm run build,生成的dist以下:
|- /dist
|- index.html
|- login.html
+ |- /css
+ |- index.css
+ |- login.css
|- /js
(略)
复制代码
index.css和login.css都包含了公用样式,还能够进一步优化,把公用样式分离出来。
修改webpack.common.js,使用正则,把src/css/common/下的css单独打包并引用。
...
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/html/index.html',
M chunks: ['style', 'jquery', 'index']
}),
new HtmlWebpackPlugin({
filename: 'login.html',
template: './src/html/login.html',
M chunks: ['style', 'jquery', 'login']
}),
new MiniCssExtractPlugin({
filename: 'css/[name].css'
})
],
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /jquery/,
name: 'jquery',
chunks: 'all'
},
+ styles: {
+ test: /[\\/]common[\\/].+\.css$/,
+ name: 'style',
+ chunks: 'all',
+ enforce: true
+ }
}
}
},
复制代码
执行npm run build,生成的dist以下:
|- /dist
|- index.html
|- login.html
+ |- /css
+ |- index.css
+ |- login.css
|- style.css <-- 公用css
|- /js
|- index.js
|- login.js
|- jquery.js
|- style.js <-- 怎么会有这个?
复制代码
发如今dist/js/目录下会生成一个多余的style.js,而且html也会引用这个多余的js。这是webpack4的bug,从2016年到如今处于open状态未解决,第三方插件都试过了,目前尚未解决,期待在webpack5中能够解决。
若是每一个页面都有一个header,就能够把header抽成html模块,而后在须要的页面引入。这里经过ejs来实现。ejs本质仍是个html,只不过多了些模板语法。
npm install ejs-loader --save-dev
复制代码
以index.html为例,把index.html重命名为index.ejs
plugins: [
...
new HtmlWebpackPlugin({
filename: 'index.html',
+ // 这里将html改为ejs
M template: './src/html/index.ejs',
chunks: ['style', 'jquery', 'index']
}),
...
module: {
rules: [
...
+ {
+ test: /\.ejs/,
+ use: ['ejs-loader'],
+ }
...
复制代码
建立src/html/components/header/header.ejs
<div id="header" class="G-header">这是公用头部</div>
复制代码
在src/html/index.ejs引入便可。
...
<div id="app">
+ <%= require('./components/header/header.ejs')() %>
<div id="info"></div>
</div>
...
复制代码
本章节介绍如何在css和html中引用图片。
npm install file-loader url-loader --save-dev
复制代码
修改webpack.common.js
module: {
rules: [
...
+ {
+ test: /\.(png|svg|jpg|gif|webp)$/,
+ use: [
+ {
+ loader: 'url-loader',
+ options: {
+ // 最终生成的css代码中,图片url前缀
+ publicPath: '../images',
+ // 图片输出的实际路径(相对于dist)
+ outputPath: 'images',
+ // 当小于某KB时转为base64
+ limit: 0
+ }
+ }
+ ]
+ }
...
]
},
复制代码
在src/images里加入图片1.jpg
|- /src
|- /css
(略)
|- /html
(略)
+ |- /images
+ |- 1.jpg
|- /js
(略)
|- /static
(略)
复制代码
在src/css/pages/index.styl加入代码:
.bg-pic
width: 200px
height: 200px
background: url(../../images/1.jpg) no-repeat
复制代码
在src/html/index.ejs加入代码:
<div id="app">
<%= require('./components/header/header.ejs')() %>
<div id="info"></div>
+ <div class="bg-pic"></div>
</div>
复制代码
执行npm run build,图片可正常访问,生成dist目录以下:
|- /dist
|- /css
(略)
|- /images
+ |- f0a89ff457b237711f8306a000204128.jpg
|- /js
(略)
|- /static
(略)
|- index.html
|- login.html
复制代码
html加载图片的方式就是img加载图片,须要提取html中的图片地址,须要安装插件html-loader
npm install html-loader --save-dev
复制代码
在src/images里加入图片2.jpg
|- /src
|- /css
(略)
|- /html
(略)
|- /images
|- 1.jpg
+ |- 2.jpg
|- /js
(略)
|- /static
(略)
复制代码
修改webpack.common.js,这样能够把html中的图片提取并打包。
module: {
rules: [
...
+ {
+ test: /\.(html)$/,
+ use: {
+ loader: 'html-loader',
+ options: {
+ attrs: ['img:src', 'img:data-src', 'audio:src'],
+ minimize: true
+ }
+ }
+ }
...
复制代码
在src/html/index.ejs加入代码:
<div id="app">
<%= require('./components/header/header.ejs')() %>
<div id="info"></div>
<div class="bg-pic"></div>
+ <img src="${require('../images/2.jpg')}" alt="">
</div>
复制代码
执行npm run build,图片已可正常访问,生成dist目录以下
|- /dist
|- /css
(略)
|- /images
|- f0a89ff457b237711f8306a000204128.jpg
+ |- dab63db25d48455007edc5d81c476076.jpg
|- /js
(略)
|- /static
(略)
|- index.html
|- login.html
复制代码
可是发现html中img的图片不能显示。查看生成的代码发现:
修改webpack.common.js,将MiniCssExtractPlugin.loader改成对象的方式:
module: {
rules: [
...
{
test: /\.css$/,
use: [
M {
M loader: MiniCssExtractPlugin.loader,
M options: {
M // css中的图片路径增长前缀
M publicPath: '../'
M }
M },
'css-loader'
]
},
{
test: /\.styl$/,
use: [
M {
M loader: MiniCssExtractPlugin.loader,
M options: {
M // css中的图片路径增长前缀
M publicPath: '../'
M }
M },
'css-loader',
'stylus-loader'
]
},
...
{
test: /\.(png|svg|jpg|gif|webp)$/,
use: [
{
loader: 'url-loader',
options: {
D // 最终生成的图片路径代码 (删除)
D // publicPath: '../images', (删除)
// 图片输出的实际路径
outputPath: 'images',
// 当小于某KB时转为base64
limit: 0
}
}
]
},
...
复制代码
再执行npm run build,路径显示正常了。
从阿里巴巴图标网站 www.iconfont.cn/ 下载字体和样式文件,导入到项目中,结构以下:
|- /src
|- /css
|- /common
|- common.css
|- frame.css
+ |- iconfont.css
|- reset.css
|- /pages
|- index.styl
|- login.styl
+ |- /fonts
+ |- iconfont.eot
+ |- iconfont.svg
+ |- iconfont.ttf
+ |- iconfont.woff
+ |- iconfont.woff2
|- /html
(略)
|- /images
(略)
|- /js
(略)
|- /static
(略)
复制代码
src/css/common/frame.css里要@import "iconfont.css",而后修改iconfont.css中每一个字体的路径。
<i class="G-iconfont G-ficon-cart"></i>
复制代码
修改webpack.common.js,
module: {
rules: [
...
+ {
+ test: /\.(woff|woff2|eot|ttf|svg)$/,
+ use: {
+ loader: 'file-loader',
+ options: {
+ // 保留原文件名和后缀名
+ name: '[name].[ext]',
+ // 输出到dist/fonts/目录
+ outputPath: 'fonts',
+ }
+ }
+ }
]
},
复制代码
执行npm run build, 生成dist目录以下:
|- /dist
|- /css
(略)
|- /images
(略)
+ |- /fonts
|- iconfont.eot
|- iconfont.svg
|- iconfont.ttf
|- iconfont.woff
|- /js
(略)
|- /static
(略)
|- index.html
|- login.html
复制代码
没有生成woff2文件,是由于css中没有引用。