修改输出资源的名称和路径
1、配置
js
const path = require('path')
module.exports = {
entry: './src/main.js',
output: {
// 所有文件输出目录
path: path.resolve(__dirname, 'dist'),
filename: '/static/js/main.js' // 将 js 文件输出到 static/js 目录中
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},{
test: /\.less$/,
use: ['style-loader', 'css-loader', 'less-loader']
},
{
test: /\.s[ac]ss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.styl$/,
use: ['style-loader', 'css-loader', 'stylus-loader']
},
{
test: /\.(png|jpe?g|gif|svg)$/,
use: 'asset',
parse: {
dataUrlCondition: {
maxSize: 10 * 1024 // 10kb
}
},
generator: {
// 将图片文件输出到 static/imgs 目录中
// 将图片文件命名 [hash:8][ext][query]
// [hash:8]: hash值取8位
// [ext]: 使用之前的文件扩展名
// [query]: 添加之前的query参数
filename: 'static/img/[hash:8][ext][query]'
}
},
]
},
plugins: [],
mode: 'development'
}
2、修改index.html
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>webpack5</title>
</head>
<body>
<h1>Hello Webpack5</h1>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
<div class="box5"></div>
<!-- 修改 js 资源路径 -->
<script src="../dist/static/js/main.js"></script>
</body>
</html>
3、运行指令
npx webpack
此时输出的文件目录(需要清空原来的dist文件夹):
├── dist
└── static
├── imgs
│ └── 7003350e.png
└── js
└── main.js