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"
  }
}
相关推荐
apcipot_rain1 小时前
【应用密码学】实验五 公钥密码2——ECC
前端·数据库·python
ShallowLin2 小时前
vue3学习——组合式 API:生命周期钩子
前端·javascript·vue.js
Nejosi_念旧2 小时前
Vue API 、element-plus自动导入插件
前端·javascript·vue.js
互联网搬砖老肖2 小时前
Web 架构之攻击应急方案
前端·架构
pixle02 小时前
Vue3 Echarts 3D饼图(3D环形图)实现讲解附带源码
前端·3d·echarts
麻芝汤圆3 小时前
MapReduce 入门实战:WordCount 程序
大数据·前端·javascript·ajax·spark·mapreduce
juruiyuan1115 小时前
FFmpeg3.4 libavcodec协议框架增加新的decode协议
前端
Vone_665 小时前
node.js 邮箱验证服务器搭建
运维·服务器·node.js
Peter 谭5 小时前
React Hooks 实现原理深度解析:从基础到源码级理解
前端·javascript·react.js·前端框架·ecmascript
程序员拂雨6 小时前
HTTP和HTTPS模块
http·https·node.js