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"
  }
}
相关推荐
又又呢18 分钟前
前端面试题总结——webpack篇
前端·webpack·node.js
dog shit1 小时前
web第十次课后作业--Mybatis的增删改查
android·前端·mybatis
我有一只臭臭1 小时前
el-tabs 切换时数据不更新的问题
前端·vue.js
七灵微1 小时前
【前端】工具链一本通
前端
Nueuis2 小时前
微信小程序前端面经
前端·微信小程序·小程序
_r0bin_5 小时前
前端面试准备-7
开发语言·前端·javascript·fetch·跨域·class
IT瘾君5 小时前
JavaWeb:前端工程化-Vue
前端·javascript·vue.js
potender5 小时前
前端框架Vue
前端·vue.js·前端框架
站在风口的猪11085 小时前
《前端面试题:CSS预处理器(Sass、Less等)》
前端·css·html·less·css3·sass·html5
程序员的世界你不懂6 小时前
(9)-Fiddler抓包-Fiddler如何设置捕获Https会话
前端·https·fiddler