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"
  }
}
相关推荐
前端Hardy16 分钟前
HTML&CSS:有趣的漂流瓶
前端·javascript·css
前端Hardy17 分钟前
HTML&CSS :惊艳 UI 必备!卡片堆叠动画
前端·javascript·css
无羡仙41 分钟前
替代 Object.freeze 的精准只读模式
前端·javascript
web前端1231 小时前
Java客户端开发指南 - 与Web开发对比分析
前端
龙在天1 小时前
前端 9大 设计模式
前端
搞个锤子哟1 小时前
网站页面放大缩小带来的问题
前端
hj5914_前端新手1 小时前
React 基础 - useState、useContext/createContext
前端·react.js
半花1 小时前
【Vue】defineProps、defineEmits 和 defineExpose
前端·vue.js
霍格沃兹_测试1 小时前
软件测试 | 测试开发 | H5页面多端兼容测试与监控
前端
toooooop81 小时前
本地开发环境webScoket调试,保存html即用
前端·css·websocket