webpack:从0到1实现一个plugin

下面演示的是,生成html文件并引入bundle文件

webpack.config.js
const MyPlugin = require('./myplugin.config')

module.exports = {
    entry: './index.js',
    output: {
        filename: 'main.js'
    },
    plugins: [
        new MyPlugin()
    ],
    mode: 'development'
}
index.js
let a = 1
a+= 1
console.log('index.js')
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;
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"
  }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值