项目结构为
其中
index.html
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="app"></div>
<!--导入 Webpack 输出的 JavaScript 文件-->
<script src="./dist/bundle.js"></script>
</body>
</html>
main.js
import show from './show.js';
show('WebPackerKKKKKKKKKKKKKKKKKKKKKKK');
show.js
import css from './main.css';
// 操作 DOM 元素,把 content 显示到网页上
function show(content) {
window.document.getElementById('app').innerText = 'Hello,' + content;
}
// 通过 CommonJS 规范导出 show 函数
export default show;
main.css
#app{
text-align: center;
}
webpack.config.js
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
// JavaScript 执行入口文件
entry: './main.js',
output: {
// 把所有依赖的模块合并输出到一个 bundle.js 文件
filename: 'bundle.js',
// 输出文件都放到 dist 目录下
path: path.resolve(__dirname, './dist'),
},
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"]
}
]
},
devServer: {
publicPath:"./dist",
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000,
},
plugins: [
new MiniCssExtractPlugin({
filename: `[name].css`
})
]
};
package.json
{
"devDependencies": {
"css-loader": "^5.2.4",
"mini-css-extract-plugin": "^1.6.0",
"serve": "^11.3.2",
"webpack": "^5.37.1",
"webpack-cli": "^4.7.0",
"webpack-dev-server": "^3.11.2"
},
"scripts": {
"bulid":"node_modules/.bin/webpack",
"dev": "webpack serve --open"
}
}
记得给项目npm install掉package.json上面的依赖.
运行dev server后发现只有被css和js文件被打包了,而index.html不知道去哪了,不知道是哪的配置问题。
problem solved,把index.html放到dist文件夹里面就行了