webpack:从0到1实现一个plugin

下面演示的是,生成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"
  }
}
相关推荐
iCoding9110 小时前
前端分页 vs 后端分页:技术选型
前端·后端·系统架构
mingtianyihou3310 小时前
使用 Service Worker 限制请求并发数
前端
张可爱10 小时前
20251017-Vue2八股文整理(上篇)
前端
FanetheDivine10 小时前
ts中如何描述一个复杂函数的类型
前端·typescript
lightgis10 小时前
chrome中的axure插件提示无法不受支持
前端·chrome
速易达网络10 小时前
Vue3 原生移动应用开发来了
前端·javascript·css
GISer_Jing10 小时前
LLM对话框项目技术栈&重难点总结
前端·ai·node.js
我爱学习_zwj11 小时前
【鸿蒙进阶-7】鸿蒙与web混合开发
前端·华为·harmonyos
小谭鸡米花11 小时前
高德地图电子围栏/地图选区/地图打点
前端·javascript·vue.js
摆烂工程师11 小时前
什么是 ChatGPT Business 会员?与 ChatGPT Plus 有什么不同?
前端·后端·程序员