命令:
npm init -y
npm install webpack webpack-cli --save-dev
在项目的根目录下启动 cmd,执行 webpack 命令会出现不是内部或外部命令(因为是本地安装),可以执行以下命令构建:
npx webpack
webpack.config.js配置文件在项目根目录下创建 webpack.config.js 文件,配置内容如下:
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist')
},
mode: 'development'
}
在 package.json 中配置 npm script 脚本:
{
"scripts": {
"build": "webpack"
}
}
此时,打包命令如下:
npm run build
以 html-webpack-plugin 为例,安装:
npm install html-webpack-plugin --save-dev
在 webpack.config.js 文件添加以下配置:
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist'),
clean: true // 清除旧的打包文件
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html', // 模板位置
filename: 'index.html', // 打包后的html文件名称
inject: 'body' // script标签位置,可选值:body/head
})
]
}
需要在项目根目录创建 index.html 模板文件。
mode 模式开发模式
module.exports = {
mode: 'development'
}
生产模式
module.exports = {
mode: 'production'
}
区别:开发模式打包的 .js 文件没有压缩,并且显示详细信息;开发模式打包的 .js 文件是压缩后的文件
代码异常时定位到源码,在 webpack.config.js 文件中配置:
module.exports = {
devtool: 'inline-source-map'
}
devtool 字段的模式包括:
| 模式 | 说明 |
|---|---|
eval | 每个 module 会封装到 eval 里包裹起来执行,并且会在末尾追加注释 //@ sourceURL |
source-map | 生成一个 SourceMap 文件 |
inline-source-map | 生成一个 DataURL 形式的 SourceMap 文件 |
hidden-source-map | 和 source-map 一样,但不会在 bundle 末尾追加注释 |
eval-source-map | 每个 module 会通过 eval() 来执行,并且生成一个 DataURL 形式的 SourceMap |
cheap-source-map | 生成一个没有列信息(column-mappings)的 SourceMaps 文件,不包括 loader 的 sourcemap (譬如 babel 的 sourcemap) |
cheap-module-source-map | 生成一个没有列信息(column-mappings)的 SourceMap 文件,同时 loader 的 sourcemap 也被简化为只包含对应行的 |
修改 package.json 中的 npm script 脚本:
{
“scripts”: {
"build": "webpack --watch"
}
}
安装:
npm install webpack-dev-server --save-dev
配置 npm script :
{
"scripts": {
"dev": "webpack-dev-server",
"build": "webpack --watch"
}
}
启动服务:
npm run dev
在浏览器中访问项目 http://127.0.0.1:8080/
配置默认打开浏览器:
{
"scripts": {
"dev": "webpack-dev-server --open",
}
}
webpack.config.js 文件配置本地服务器:
const path = require('path')
module.exports = {
devServer: {
static: path.resolve(__dirname, './dist'),
compress: true, // 服务器端是否进行代码压缩,传输 zip 压缩包
port: 8080, // 端口号
host: '0.0.0.0', //
headers: { // 配置响应头
'X-Access-Token': 'xxx'
},
proxy: {
'/api': {
target: 'http://192.168.1.100:3000', // 真实的服务器地址
pathRewrite: {
'^/api': ''
}
}
},
https: { // 配置HTTPS证书
cacert: './server.pem',
pfx: './server.pfx',
key: './server.key',
cert: './server.crt',
passphrase: 'webpack-dev-server',
requestCert: true
},
historyApiFallback: true, // 配置 SPA 应用的 history 路由模式
hot: true, // 模块热替换
liveReload: true, // 开启热更新
}
}
(1)resource资源
// webpack.config.js
module.exports = {
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist'),
clean: true,
assetModuleFilename: 'image/[contenthash][ext]' // 自定义静态资源打包目录与名称
},
module: {
rules: [
{
test: /\.jpg|\.png$/,
type: 'asset/resource', // 发送一个单独文件的URL
generator: {
filename: 'images/[contenthash][ext]' // 优先级高于 output.assetModuleFilename
}
}
]
}
}
(2)inline资源
不会打包出任何静态资源文件
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.jpg|\.png$/,
type: 'asset/inline' // 导出一个资源的Data URI,页面中的图片为 base64
}
]
}
}
(3)source资源
不会打包出任何静态资源文件
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.txt$/,
type: 'asset/source' // 导出资源的源代码
}
]
}
}
通用资源类型 asset,在导出一个 data URI 和发送一个单独的文件之间自动选择。
默认地,当文件小于 8kb 时,将会被视为 inline 模块类型,否则会被视为 resource 模块类型。可以在 module rule 层级中,设置 Rule.parser.dataUrlCondition.maxSize 选项来修改条件。修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.jpg$/,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 200 * 1024 // 小于200kb是为 inline 模式
}
}
}
]
}
}
需要安装 css 相关的 loader:
npm install css-loader style-loader --save-dev
css-loader 用于编译 css 文件,style-loader 用于将 css 代码加载到 .html 模板文件中。
配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'] // loader执行顺序为逆向加载(数组元素的倒序)
}
]
}
}
在项目中引入 sass,安装 sass 和 sass-loader:
npm install sass sass-loader --save-dev
修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(css|scss)$/,
use: ['style-loader', 'css-loader', 'sass-loader'] // loader执行顺序为逆向加载(数组元素的倒序)
}
]
}
}
要以模块化的方式将
.css和.scss样式文件引入.js文件中
需要安装插件:
npm install mini-css-extract-plugin --save-dev
mini-css-extract-plugin插件最小支持webpack5版本
修改配置文件:
// webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
plugins: [
new MiniCssExtractPlugin({
filename: 'style/[contenthash].css'
})
],
module: {
rules: [
{
test: /\.(css|scss)$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
}
]
}
}
安装插件:
npm install css-minimizer-webpack-plugin --save-dev
修改配置文件:
// webpack.config.js
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
module.exports = {
mode: 'production',
optimization: {
minimizer: [
new CssMinimizerPlugin()
]
}
}
配置完成后,执行构建命令 npm run build, 打包后的 css 代码就被压缩了。
fonts 字体修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
type: 'asset/resource'
}
]
}
}
(1)加载 csv 、tsv 文件
安装:
npm install csv-loader --save-dev
修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(csv|tsv)$/,
use: ['csv-loader']
}
]
}
}
(2)加载 xml 文件
安装:
npm install xml-loader --save-dev
修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.xml$/,
use: ['xml-loader']
}
]
}
}
(3)加载 yaml 文件
安装依赖:
npm install yaml --save-dev
修改配置文件:
// webpack.config.js
const yaml = require('yaml')
module.exports = {
module: {
rules: [
{
test: /\.yaml$/,
type: 'json',
parser: {
parse: yaml.parse
}
}
]
}
}
(4)加载 toml 文件
安装依赖:
npm install toml --save-dev
修改配置文件:
// webpack.config.js
const toml = require('toml')
module.exports = {
module: {
rules: [
{
test: /\.toml$/,
type: 'json',
parser: {
parse: toml.parse
}
}
]
}
}
(5)加载 json5 文件
webpack 默认可以编译 json 文件,如果使用了升级版的 .json5 文件,需要安装依赖:
npm install json5 --save-dev
修改配置文件:
// webpack.config.js
const json5 = require('json5')
module.exports = {
module: {
rules: [
{
test: /\.json5$/,
type: 'json',
parser: {
parse: json5.parse
}
}
]
}
}
ES6转ES5将 ES6 代码转为 ES5 代码需要 babel-loader 加载器,其中:
babel-loader:在 webpack 中应用 babel 解析 ES6 的桥梁;@babel/core:babel 核心模块;@babel/preset-env:babel 预设,一组 babel 插件的集合。安装:
npm install babel-loader @babel/core @babel/preset-env --save-dev
修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
}
还需要再安装 regeneratorRuntime 插件,它是 webpack 打包生成的全局辅助函数,有 babel 生成,用于兼容 async/await 语法。
安装插件:
# 生产环境运行时需要这个插件,要安装到生产环境依赖
npm install @babel/runtime --save
# 编译时需要在使用 regeneratorRuntime 的地方自动 require 导包
npm install @babel/plugin-transform-runtime --save-dev
修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: [
['@babel/plugin-transform-runtime']
]
}
}
}
]
}
}
eslint安装 eslint
npm install eslint --save-dev
初始化 .eslintrc 文件,执行以下命令自定生成:
npx eslint --init
在控制台中选择如下:
$ npx exlint --init
√ How would you like to use ESLint? · style
√ What type of modules does your project? · esm
√ Which framework does your project use? · none
√ Does your project use TypeScript? · No
√ Where does your code run? · browser
√ How would you like to dofine a sytle for your project? · guide
√ Which style guide do you want to follow? · airbnb
√ What format do you want your config file to be in? · JSON
.eslintrc 文件的默认配置如下:
env:设置脚本的运行环境;extends:继承社区整理好的配置规则,例如 eslint-plugin-react/recommended 使用社区的 react 规则;plugins:添加的插件,为 eslint 增加新的检查规则,例如 eslint-plugin-react 是对 react 项目的检查规则;parser:配置解析项目的规则,例如 @typescript-eslint/parser;parserOptions:搭配 parser ,指定需要支持的 javascript 语言选项;globals:当访问当前源文件内未定义的变量时,no-undef 规则将发出警告。如果你想在一个源文件里使用全局变量,推荐你在 ESLint 中定义这些全局变量,这样 ESLint 就不会发出警告了;readonly 表示可读不可写,writable 表示可读可写;rules:具体的规则,off 或 0 表示关闭规则;warn 或 1 表示使用警告级别开启规则(不会退出程序);error 或 2 表示使用错误级别开启规则(触发规则会退出程序)。结合 webpack 使用
安装:
npm install eslint-loader --save-dev
修改 webpack.config.js 文件:
module.exports = {
module: {
rules: [
{
test: /\.(js | jsx)$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
}
]
},
devServer: {
client: {
overlay: true // 默认为true,即开启热更新功能
}
}
}