webpack.config.js:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizePlugin = require('css-minimizer-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
filename: 'app.js',
path: path.resolve(__dirname, './dist'),
clean: true,
assetModuleFilename: 'images/[contenthash][ext]'
},
devtool: 'inline-source-map',
mode: 'production',
devServer: {
static: './dist'
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
filename: 'app.html',
inject: 'body'
}),
new MiniCssExtractPlugin({
filename: '/css/[contenthash].css'
})
],
module: {
rules: [
{
test: /\.(jpeg|png)$/,
type: 'asset/resource'
},
{
test: /\.txt$/,
type: 'asset/source'
},
{
test: /\.(css|less)$/,
use: [ MiniCssExtractPlugin.loader, 'css-loader', 'less-loader' ]
}
]
},
optimization: {
minimizer: [
new CssMinimizePlugin() // mode 为 production 才会生效
]
}
}
package.json:
{
"name": "webpack-01",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "npx webpack",
"server": "npx webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^6.5.1",
"css-minimizer-webpack-plugin": "^3.2.0",
"html-webpack-plugin": "^5.5.0",
"less": "^4.1.2",
"less-loader": "^10.2.0",
"mini-css-extract-plugin": "^2.4.5",
"npx": "^10.2.2",
"style-loader": "^3.3.1",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.6.0"
}
}
dist/app.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>webpack-01</title>
<link href="/css/12b52682f3040bb1646a.css" rel="stylesheet"></head>
<body>
<script defer src="app.js"></script>
</body>
</html>
src/hello.js:
function hello () {
console.log('hello!!! webpack')
}
export default hello
src/index.js:
项目结构: