webpack的功能
- 打包:将不同的类型的资源按照模块处理进行打包
- 静态:打包后最终产出静态资源
- webpack支持不同规范的模块化开发
体验webpack
依赖导图
文件
webpack.config.js 依赖
babel.config.js依赖
postcss.config.js依赖
安装流程
安装webpack
yarn webpack webpack-cli
新建webpack配置文件
touch webpack.config.js
安装webpack 插件依赖
yarn add html-webpack-plugin copy-webpack-plugin webpack-dev-server -D
安装 webpack loader
yarn add css-loader style-loader postcss-loader postcss postcss-preset-env sass-loader sass -D
安装babel preset 和插件
yarn add babel-loader @babel/core @babel/preset-env core-js@3 -D
新建 babel.config.js 文件
{
"presets": [
[
"@babel/preset-env",
{
// 按需加载
"useBuiltIns": "usage",
"corejs": {
"version": 3
}
}
]
]
}
新建 .browserslistrc 文件
>1%
last 2 version
ie 9-11
新建 postcss.config.js 文件
module.exports = {
plugins: ["postcss-preset-env"],
};
webpack.config.js 文件内容
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
const { DefinePlugin } = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const publicPath = '';
module.exports = {
mode: 'development',
target: 'web',
entry: './src/index.js',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
publicPath: publicPath,
clean: true,
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
devServer: {
port: '3001', // 默认是 8080
hot: true,
hotOnly: true,
stats: 'errors-only', // 终端仅打印 error
compress: true, // 是否启用 gzip 压缩
publicPath: publicPath,
contentBase: path.resolve(__dirname, './public'),
watchContentBase: true,
proxy: {
'/api': {
target: 'http://0.0.0.0:80',
pathRewrite: {
'/api': '',
},
},
},
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
'postcss-loader',
],
},
{
test: /\.scss$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 2,
},
},
'postcss-loader',
'sass-loader',
],
},
{
test: /\.(png|jpe?g|gif|svg)$/,
// type: "asset/resource", file-loader的效果
// type: "asset/inline", url-loader
type: 'asset',
generator: {
filename: 'img/[name].[hash:6][ext]',
},
parser: {
dataUrlCondition: {
maxSize: 1 * 1024,
},
},
},
{
test: /\.js$/,
use: 'babel-loader',
exclude: [[path.resolve(__dirname, 'node_modules')]],
},
],
},
plugins: [
new htmlWebpackPlugin({
template: path.resolve(__dirname, './public/index.html'),
title: 'webpack5配置文件',
}),
new DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
new CopyWebpackPlugin({
patterns: [
{
from: 'public',
to: 'static',
globOptions: {
ignore: ['**/index.html', '**/.DS_Store', '**/abc.txt'],
},
},
],
}),
],
};
依赖总结
webpack5
- webpack
- webpack-cli
- plugin
- html-webpack-plugin
- copy-webpack-plugin
- webpack-dev-server
- loader
- css-loader style-loader postcss-loader sass-loader babel-loader
- 其他
- sass
babel 插件
- @babel/core
- @babel/preset-env
- core-js@3
postcss 插件
- postcss
- ppostcss-preset-env