简单搭建的 Webpack 5 开发环境
首先进入目标文件夹
# 初始化项目
npm init -y
# 安装 webpack
npm i webpack webpack-cli --save-dev
# 安装插件
npm i html-webpack-plugin clean-webpack-plugin copy-webpack-plugin --save-dev
# js 处理
# 安装 babel
npm i @babel/core @babel/preset-env @babel/plugin-transform-runtime babel-loader --save-dev
# css 处理
# 安装 laoder
npm i css-loader sass-loader node-sass --save-dev
# 安装 mini-css-extract-plugin 插件
npm i mini-css-extract-plugin --save-dev
# 启动服务
# 安装 webpack-dev-server
npm i webpack-dev-server --save-dev
创建文件
|-- demo
|-- babel.config.js
|-- package-lock.json
|-- package.json
|-- webpack.config.js
|-- src
|-- index.html
|-- css
| |-- index.css
|-- file
| |-- test.txt
|-- js
| |-- index.js
|-- sass
| |-- index.scss
|-- static
|-- image
|-- unnamed.jpg
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="test">
<div class="test-1"></div>
</div>
<img src="./static/image/unnamed.jpg"/>
</body>
</html>
// index.js
import '../css/index.css'
import '../sass/index.scss'
import txt from '../file/test.txt'
const fn = () => {
console.log('fn')
}
fn()
async function asyncFn () {
return await Promise.resolve('p')
}
asyncFn().then(data => {
console.log(data)
})
console.log(txt)
// index.css
.test {
height: 100px;
width: 100px;
background-color: #ccc;
}
// index.scss
.test {
.test-1 {
width: 50px;
height: 50px;
background-image: url('../static/image/unnamed.jpg');
background-repeat: no-repeat;
}
}
配置
// webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin') // 用于生成入口HTML,index.html
const { CleanWebpackPlugin } = require('clean-webpack-plugin') // 重新打包时清除旧文件
const CopyWebpackPlugin = require('copy-webpack-plugin') // 文件复制
const MiniCssExtractPlugin = require('mini-css-extract-plugin') // 打包 .css 独立文件
/** @type import('webpack').Configuration */
const config = {
entry: './src/js/index.js', // 输入
output: { // 输出
filename: 'static/js/[name]-[hash:8].js', // 输出文件名称 name:chunk 名称;hash8:八位哈希值
path: path.join(__dirname, './dist'), // 路径(绝对路径)
environment: {
arrowFunction: false // 不使用箭头函数
}
},
mode: 'development', // 开发模式
module: { // 处理模块
rules: [{ // 处理规则
test: /\.js$/i, // 匹配 .js 文件
use: ['babel-loader'], // 处理的 loader
exclude: /node_modules/, // 排除 node_modules
// options: { 注释,采用 babel.config.js 方式配置
// presets: ['@babel/env'],
// plugins: ['@babel/plugin-transform-runtime']
// }
}, {
test: /\.(css$|scss$)/i, // 匹配 .css/.scss 文件
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'], // 处理的 loader
// MiniCssExtractPlugin.loader 将处理完的代码打包成 .css 独立文件
resource: {
not: [/node_modules/] // 排除 node_modules 等效于 exclude: /node_modules/
},
}, {
test: /\.(png|jpe?g|gif|svg)$/i, // 匹配图片类型
type: 'asset', // 使用 webpack 自身的处理资源 等同于 url-loader
generator: {
filename: 'static/image/[name].[hash:6][ext]' // 生成的文件名称 ext:后缀
},
parser: {
dataUrlCondition: {
maxSize: 10 * 1024, // 文件大小 10k,小于 10k 采用 base64 的方式
}
}
}, {
test: /\.(xml|txt)$/i, // 匹配文件类型
type: 'asset/source' // 等同于 raw-loader
}]
},
devtool: 'eval-source-map', // 用于浏览器调试
/** @type import('webpack-dev-server').Configuration */
devServer: { // 服务配置
port: 9000, // 端口
contentBase: path.resolve(__dirname, 'dist'), // 本地路径
open: true, // 打开浏览器
publicPath: '/' // 资源路径
// 新版本配置
// static: {
// directory: path.resolve(__dirname, 'dist'), // contentBase
// publicPath: '/' // publicPath
// },
},
plugins: [ // 插件
new HtmlWebpackPlugin({
filename: 'index.html', // 输出文件名
template: './src/index.html' // 模板文件名
}),
new CopyWebpackPlugin({
patterns: [ // 文件复制, 从 src/static/ 复制到 dist/static
{ from: path.resolve(__dirname, 'src/static/'), to: 'static' },
]
}),
new MiniCssExtractPlugin({ // 输出 .css 文件
filename: 'static/css/styles-[hash:8].css' // 文件名称
}),
new CleanWebpackPlugin() // 清除旧文件
]
}
module.exports = config // 导出配置
// babel.config.js
module.exports = {
presets: ['@babel/env'],
plugins: ['@babel/plugin-transform-runtime']
}
// package.json
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "npx webpack-dev-server", // 启动服务
"build": "npx webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.14.8",
"@babel/plugin-transform-runtime": "^7.14.5",
"@babel/preset-env": "^7.14.8",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^4.0.0-alpha.0",
"copy-webpack-plugin": "^9.0.1",
"css-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2",
"mini-css-extract-plugin": "^2.1.0",
"node-sass": "^6.0.1",
"sass-loader": "^12.1.0",
"webpack": "^5.46.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {}
}
启动
npm run dev
Tip
如果启动遇到
Error: Cannot find module 'webpack-cli/bin/config-yargs'
报错,可以将 webpack-cli 降级npm i webpack-cli@3 --save-dev
webpack-dev-server
服务会将文件打包到内存中,启动时不会在dist
下产生文件,注意可能存在的路径问题如果想直接导入到
index.html
不生成.css
独立文件,可使用style-loader
同时将MiniCssExtractPlugin.loader
替换成'style-loader'
即可# 安装 npm i style-loader --save-dev
记得去掉插件项内的
new MiniCssExtractPlugin({ filename: 'static/css/styles-[hash:8].css' }),
使用
less
# 安装 npm i less-loader less --save-dev
替换
'sass-loader'
,注意修改匹配项更多 webpack 配置 可参考