Modify the name and path of output resources
If you need to modify the name and path of Webpack output resources, you can do so by configuring the output
option.
Configuration
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'static/js/main.js', // Output js files to the static/js directory
},
module: {
rules: [
{
// Used to match files ending with .css
test: /\.css$/,
// The order of Loader execution in the use array is from right to left
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|webp)$/,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 10 * 1024, // Images less than 10kb will be processed by base64
},
},
generator: {
// Output the image file to the static/imgs directory
// Name the image file [hash:8][ext][query]
// [hash:8]: The hash value is 8 bits
// [ext]: Use the previous file extension
// [query]: add the previous query parameter
filename: 'static/imgs/[hash:8][ext][query]',
},
},
],
},
plugins: [],
mode: 'development',
};
Modify index.html
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>webpack5</title>
<!-- Import the packaged js file to see the effect -->
<script src="../dist/static/js/main.js"></script>
</head>
<body>
<h1>Hello Webpack5</h1>
<!-- Prepare a DOM container with styles -->
<div class="box1"></div>
<!-- Prepare a second DOM container with styles -->
<div class="box2"></div>
<!-- Prepare the third and fourth DOM containers with styles -->
<div class="box3"></div>
<div class="box4"></div>
<!-- Prepare the fifth DOM container with styles -->
<div class="box5"></div>
</body>
</html>
Run command
npx webpack
Output file directory at this time: (Note: You need to clear the files generated by the last packaging and re-packaging to achieve the effect)