下面演示的是,生成html文件并引入bundle文件
c
webpack.config.js
const MyPlugin = require('./myplugin.config')
module.exports = {
entry: './index.js',
output: {
filename: 'main.js'
},
plugins: [
new MyPlugin()
],
mode: 'development'
}
c
index.js
let a = 1
a+= 1
console.log('index.js')
c
myplugin.config.js
const fs = require('fs');
const path = require('path');
const template = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Webpack Bundle</title>
</head>
<body>
<div>Hello from Webpack</div>
<!-- Webpack will inject bundles here -->
</body>
</html>`;
class MyCustomHtmlWebpackPlugin {
apply(compiler) {
compiler.hooks.emit.tapAsync('MyCustomHtmlWebpackPlugin', (compilation, callback) => {
// 找到bundle.js的输出路径
const outputPath = compilation.outputOptions.path;
const bundleFilename = compilation.outputOptions.filename;
// 假设我们要生成的index.html文件位于输出目录
const outputHtmlPath = path.resolve(outputPath, 'index.html');
// 检查index.html是否存在
fs.access(outputHtmlPath, fs.constants.F_OK, (err) => {
if (err) {
// 如果文件不存在,则使用模板创建一个新的index.html文件
// 并插入bundle.js的引用
const scriptTag = `<script src="${bundleFilename}"></script>`;
const injectedHtml = template.replace('<!-- Webpack will inject bundles here -->', scriptTag);
fs.writeFile(outputHtmlPath, injectedHtml, 'utf8', callback);
} else {
// 如果文件存在,我们可以选择读取文件、插入script标签并写回(如果需要的话)
// 但为了简化,我们在这里仅仅输出消息
console.log('index.html already exists, skipping creation.');
callback();
}
});
});
}
}
module.exports = MyCustomHtmlWebpackPlugin;
c
package.json
{
"name": "plugin",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^5.91.0",
"webpack-cli": "^5.1.4"
}
}