参看:文档地址

视频地址:https://www.bilibili.com/video/av51693431

webpack的作用:代码转换、文件优化、代码分割、模块管理、自动刷新、代码检验、自动发布

2 webpack 常见配置

2.1 安装

npm init -y
cnpm i webpack webpack-cli -D # 版本
# "webpack": "^4.41.4"
# "webpack-cli": "^3.3.10" # webpack 打包命令
npx webpack

2.2 配置

// webpack.config.js
const path = require('path')
module.exports = {
mode: 'development', // development production(该模式下回自动压缩代码)
entry: path.join(__dirname, './src/index.js'),
output: {
filename: 'bundle.[hash:8].js',
path: path.join(__dirname, './build'),
}
}

2.2.1 自定义打包配置文件

// webpack.config.xxx.js
module.exports = {
// ...
} // 执行命令
// npx webpack --config webpack.config.xxx.js

2.2.2 配置脚本

{
"scripts": {
"dev": "webpack-dev-server --config webpack.config.js --colors",
"build": "webpack --config webpack.config.js --colors"
}
}

2.3 常用插件

webpack-dev-server

cnpm i webpack-dev-server -D

devServer: {
port: 8081,
progress: true, // 进度条
contentBase: './build', // 指定 build 文件夹作为静态服务
compress: true // 压缩文件
}

html-webpack-plugin - 打包 html 页面:

cnpm i html-webpack-plugin -D

const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
// ...
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
minify: {
removeAttributeQuotes: true, // 删除双引号
collapseWhitespace: true // 折叠空行
},
hash: true // 添加 hash 戳
})
]
// ...
}

css less loader 配置

cnpm i css-loader less less-loader mini-css-extract-plugin postcss-loader style-loader url-loader -D

const MiniCssExtractPlugin = require("mini-css-extract-plugin")
module.exports = {
// ...
plugins: [
new MiniCssExtractPlugin({
filename: path.posix.join('static', 'css/[name].[contenthash].css'),
// disable: false, //是否禁用此插件
// allChunks: true,
// publicPath: '',
options: {
insert: 'head'
}
})
],
module: {
rules: [
{ // css
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// localIdentName:'[name]-[local]-[hash:base64:6]',
publicPath: '../../'
}
},
{
loader: 'css-loader',
options: {
url: true,
modules: {}
}
},
'postcss-loader'
]
},
{ // less
test: /\.less$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../../'
}
},
{
loader: 'css-loader',
options: {}
},
'less-loader',
'postcss-loader'
]
},
]
}
// ...
}

postcss.config.js

module.exports = {
plugins: {
'autoprefixer': {
overrideBrowserslist: 'last 5 version'
}
}
}

postcss-loader 配合autoprefixer给样式加前缀。

打包 JS CSS 压缩优化:

const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin') // 用于优化\最小化CSS
const TerserJSPlugin = require('terser-webpack-plugin') // js 压缩 module.exports = {
// ...
optimization: {
minimize: true,
minimizer: [
new TerserJSPlugin({
cache: true, // 是否缓存
parallel: true, // 并发打包
sourceMap: true,
}),
new OptimizeCSSAssetsPlugin({
cssProcessorPluginOptions: {
preset: ['default', { discardComments: { removeAll: true } }],
},
cssProcessorOptions: {
safe: true
}
})
]
},
// ...
}

2.4 ES6 语法转换

cnpm i @babel/preset-env @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties @babel/plugin-transform-runtime -D

cnpm i @babel/runtime -S

@babel/polyfill 已弃用,参看:core-js@3带来的惊喜corejs

require("core-js-pure/stable")
require("regenerator-runtime/runtime") module.exports = {
// ...
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: [ // 预设
["@babel/preset-env", {
"useBuiltIns": "usage",
"targets": {
"chrome": "58",
"ie": "11"
}
}]
],
plugins: [
['@babel/plugin-proposal-decorators', {'legacy': true}], // 装饰器
['@babel/plugin-proposal-class-properties', {'loose': true}], // Class
"@babel/plugin-transform-runtime"
]
}
},
include: path.resolve(__dirname, 'src'),
exclude: /node_modules/
},
]
}
// ...
}

2.5 代码规范

cnpm i eslint eslint-loader -D

// webpack.config.js
module.exports = {
// ...
module: {
rules: [
{
test: /\.js$/,
enforce: 'pre', // previous post,在mormal loader 前置执行
use: {
loader: 'eslint-loader',
options: {
cache: true,
fix: true // ESLint自动修复功能
}
},
enforce: 'pre', // previous post
exclude: /node_modules/
}
]
}
// ...
}

官方配置地址 => Rules Configuration

// .eslintrc.json
{
"parserOptions": {
"ecmaVersion": 11,
"sourceType": "module",
"ecmaFeatures": {
"globalReturn": true
}
},
"rules": {
},
"env": {
"node": true,
"commonjs": true,
"es6": true
}
}

2.6 第三方模块使用

以依赖于 jquery 为类,将module中的模块挂载到window上。

cnpm i jquery -S

  • 方法一
// expose-loader 暴露全局的loader/内联的loader 到 window上
import $ from 'expose-loader?$!jquery'
// pre 前面执行的loader normal--普通loader/内联loader/后置post-loader
console.log('window.$',window.$) // 类似于 CDN 引入文件
  • 方法二
import $ from 'jquery'
console.log('window.$',window.$)

配置:

// webpack.config.js
module.exports = {
// ...
module: {
rules: [
{ // 将 jquery 暴露给 window
test: require.resolve('jquery'),
use: 'expose-loader?$'
}
]
}
// ...
}
  • 方法三:在每个模块中注入$ 对象,不打包jquery
console.log('$', $) // 在模块中使用,但是 $ 不存在window中
// webpack.config.js
module.exports = {
// ...
plugins: [
new Webpack.ProvidePlugin({ // 在每个模块注入 $ 对象
"$": "jquery"
})
]
// ...
}
  • 方法四:CDN 引入:
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>

防止在模块中多次import jquery,导致打包体积变大:

// webpack.config.js
module.exports = {
// ...
externals: { // 不打包 jquery
jquery: 'jquery'
}
// ...
}

2.4 webpack打包图片

js中生成图片、在css插入图片、在html中插入图片

// webpack.config.js
module.exports = {
// ...
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
use: {
loader: 'url-loader',
options: {
name: path.posix.join('static', 'img/[name].[hash:7].[ext]'),
esModule: false,
limit: 5 * 1024,
// outputPath: 'img/',
// name: '[name].[hash:7].[ext]',
// publicPath:'img/'
// publicPath: 'http://www.houfee.top/' // 只为打包的图片添加 地址路径
}
}
},
]
}
// ...
}

最新文章

  1. Microsoft.Office.Interop.Excel的用法以及利用Microsoft.Office.Interop.Excel将web页面转成PDF
  2. Struts2学习笔记--使用Response下载文件和Struts2的StreamResult文件下载
  3. 配置MyBatis
  4. bootstrap-table 加载不了数据问题总结
  5. linux Xtrabackup安装及使用方法
  6. openmp在图像处理上面的运用
  7. java判断某个字符串包含某个字符串的个数
  8. [经典算法] 蒙地卡罗法求 PI
  9. System Operations on AWS - Lab 4W - Monitoring (Windows)
  10. SOSEx ReadMe
  11. WORLD OPERATS
  12. Kibana5 数据探索使用(Discover功能)
  13. 201521123065 《Java程序设计》第4周学习总结
  14. 解决IOS微信浏览器底部会出现向前向后返回按钮,返回不刷新的问题
  15. Intel格式与Motorola格式的区别
  16. 第五节: Quartz.Net五大构件之Trigger的四大触发类
  17. 初识MongoBD
  18. SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data错误的解决
  19. idea 中使用 jetty 插件
  20. angular2.0学习笔记4.npm常用指令记录及angular语法

热门文章

  1. 2018 蓝桥杯省赛 B 组模拟赛
  2. Python学习笔记之面向对象
  3. 百度统计数据导出demo的坑
  4. bzoj 4475: [Jsoi2015]子集选取
  5. 「PA2014」Kuglarz
  6. 开源Web测试工具介绍
  7. java string常用的占位符形式
  8. 读《Adaptive Thresholding Using the Integral Image》自适应图像阈值
  9. day02-Python运维开发基础
  10. 用JS写一个网站树形菜单