cnpm init
111Air:webpackSerial1 i$ cnpm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (webpackserial1)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/wangxianggui/vueProject/webpackSerial1/package.json:
{
"name": "webpackserial1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes) yes
结果
生成package.json
工程准备
新建文件
新建webpack.config.js 、 src/index.js 、dist/index.html
新建结果如下所示
+ ├─package.json
+ ├─dist // 存放最终打包的文件
+ │ └─index.html
+ ├─src // 存放入口文件等开发文件
+ │ └─index.js
+ ├─webpack.config.js // webpack的配置文件
运行cnpm install webpack webpack-cli --save-dev
安装 lodash
配置webpack.config.js
const path = require('path')
module.exports = {
entry: './src/index.js',//指定入口文件
mode: 'development',//指定开发模式
output: {
filename: "main.js",//指定输出文件名字
path: path.resolve(__dirname,'dist')//指定输出文件路径,也就是刚刚建立的dist目录
}
}
编辑src/index.js入口文件
import _ from 'lodash';
function createElement(){
let div = document.createElement('div');
div.innerHTML = _.join(['my', ' project', ' is', ' wxg'], '');
return div;
}
document.body.appendChild(createElement());
打包
npx webpack
结果
在dist 生成了main.js文件
验证开发成果
在 dist/index.html
中引入打包后的 main.js
,打开浏览器测试:
<script src="./main.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="./main.js"></script>
</body>
</html>
在webstorm 中使用预览,可以看到结果如下所示
webpack 功能测试
webpack 处理 CSS 模块
在项目 src 目录中,新建 style 文件夹,并新建 index.css 文件:
├─package.json
├─dist // 存放最终打包的文件
│ └─index.html
├─src // 存放入口文件等开发文件
│ ├─index.js
+ │ └─style
+ │ └─index.css
├─webpack.config.js // webpack的配置文件
在入口文件index.js 中新建元素方法,添加 class 为 box,这样新建的元素就带有 box 的 class 属性:
.box{
color: #00ff22;
}
css-loader : 用于处理 css 文件,使得能在 js 文件中引入使用;
使用 import './style/index.css'; 引入我们的样式文件,是没办法解析使用
style-loader : 用于将 css 文件注入到 index.html 中的 <style> 标签上;
同时在webpack.config.js 中添加 css 解析的 loader 配置:
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
}
参数介绍:
test
:需要匹配的模块后缀名; use
:对应处理的 loader 插件名称(处理顺序是从右往左)。
添加快捷打包命令
在 package.json 的 scripts 中添加一个命令为 build,以后打包只要执行 cnpm run build 即可:
"scripts": {
"build": "npx webpack -c webpack.config.js"
},
调试样式
webpack 开启 SourceMap 和添加 CSS3 前缀
在 css-loader
和 sass-loader
都可以通过设置 options
选项启用 sourceMap
。如下所示:
rules: [
{
test: /\.(sc|c|sa)ss$/,
use: [
"style-loader",
{
loader:"css-loader",
options:{ sourceMap: true }
},
{
loader:"sass-loader",
options:{ sourceMap: true }
},
]
}
]
webpack 将 CSS 抽取成单独文件
webpack4 开始使用 mini-css-extract-plugin
插件
安装插件:
cnpm install mini-css-extract-plugin --save-dev
c
npm install postcss-loader autoprefixer --save-dev
将 style-loader
,替换成 MiniCssExtractPlugin.loader
,然后添加 plugins
配置项:
const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/index.js',
mode: 'development',
output: {
filename: "main.js",
path: path.resolve(__dirname,'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader,
{
loader:"css-loader",
options:{ sourceMap: true }
},
{
loader:"postcss-loader",
options: {
ident: "postcss",
sourceMap: true,
plugins: loader => [require('autoprefixer')()]
}
},
{
loader:"sass-loader",
options:{ sourceMap: true }
},]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css', // 最终输出的文件名
chunkFilename: '[id].css'
})
]
}
在运行打包命令后,在dist目录里发现main.css文件。
在 dist/index.html
中,需要手动引入 main.css
:
// index.html
<link rel="stylesheet" href="main.css">
webpack 压缩 CSS 和 JS
使用 optimize-css-assets-webpack-plugin
压缩 CSS 的插件。
安装插件:
cnpm install optimize-css-assets-webpack-plugin --save-dev
// webpack.config.js
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
plugins: [
new OptimizeCssAssetsPlugin({})
],
}
压缩 JS
使用 uglifyjs-webpack-plugin
压缩 JS 的插件。
安装插件:
cnpm install uglifyjs-webpack-plugin --save-dev
// webpack.config.js
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
plugins: [
new UglifyJsPlugin({
cache: true, parallel: true, sourceMap: true
})
],
}
其中 UglifyJsPlugin
的参数:
cache
:当 JS 没有发生变化则不压缩;parallel
:是否启用并行压缩;sourceMap
:是否启用 sourceMap;
然后重新打包,查看 main.js
,已经被压缩了:
webpack 为文件名添加 hash 值
打包出来的 css
、js
文件是静态文件,就存在缓存问题,因此我们可以给文件名添加 hash
值,防止缓存。
添加 hash 值
直接在 webpack.config.js
中,为需要添加 hash 值的文件名添加 [hash]
就可以:
module.exports = {
// ... 省略其他
output: {
filename: 'main.[hash].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css'
}),
],
}
由于我们前面给打包的文件名添加了 hash
值,会导致 index.html
引用文件错误,所以我们需要让它能动态引入打包后的文件。
这里我们使用 HtmlWebpackPlugin
插件,它可以把打包后的 CSS 或者 JS 文件直接引用注入到 HTML 模版中,就不用每次手动修改。
安装插件:
cnpm install html-webpack-plugin --save-dev
webpack 清理目录插件
打包都会生成新的文件,并且在添加 hash
值以后,文件名不会出现重复的情况,导致旧文件的冗余。
为了解决这个问题,我们需要在每次打包之前,将 /dist
目录清空,再进行打包。
这里我们使用 clean-webpack-plugin
插件来实现。
安装插件:
npm install clean-webpack-plugin --save-dev
引入插件:
// webpack.config.js
const{CleanWebpackPlugin} =
require(
'clean-webpack-plugin');
使用插件:
// webpack.config.js
plugins: [
new
CleanWebpackPlugin()
],
附录
安装 lodash
cnpm install lodash --save-dev
--save 可以简写为-S, --save-dev可以简写为-D.