个人技术分享

下面演示的是,将代码中的var处理成const

myloader.js
module.exports = function(source) {  
    // 使用正则表达式匹配 var 声明,这里假设它们是简单的字面量或函数调用  
    const varRegex = /var (\w+)\s*=\s*([^;]+)/g;  
    let match;  
    let replacedSource = source;  
    
    // 遍历所有匹配项  
    while ((match = varRegex.exec(source)) !== null) {  
      // 检查匹配项后是否有重新赋值或其他修改  
      // 这里只是简单检查是否有后续的 = 符号,实际检查会更复杂  
      if (!/\b\w+\s*=\s*/.test(source.slice(match.index + match[0].length))) {  
        // 如果没有重新赋值,则替换为 const  
        const constDeclaration = `const ${match[1]} = ${match[2]};`;  
        replacedSource = replacedSource.replace(match[0], constDeclaration);  
      }  
    }  
    
    // 返回替换后的源代码  
    return replacedSource;  
  };
index.js

webpack.config.js
module.exports = {
    entry: './index.js',
    output: {
        filename: 'main.js'
    },
    module: {
        rules: [
            {  
                test: /\.js$/, // 匹配 .js 文件  
                exclude: /node_modules/, // 排除 node_modules 目录  
                use: [  
                  {  
                    loader: './myloader.js', // 指向你的 loader 文件的路径  
                  },  
                ],  
              },  
        ]
    },
    mode: 'development'
}
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"
  }
}