Webpack Plugin to Auto-Rename Variables

Feb 14, 2025 · 1 min read · 175 Words · -Views -Comments · Programming
Build Tools Frontend Development 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

I previously built a webpack loader called domain-replace-loader to replace domains in frontend JS, e.g., swapping to a new domain or a global window property, avoiding manual edits across repos. Sometimes the requirement isn’t about domains. A colleague recently asked to rename variables in code automatically. For example, rename T_PROJECT to P_PROJECT. I updated the plugin to support automatic variable renaming.

Approach

The core is parsing code with esprima, walking tokens, and operating based on each token’s type.

https://static.1991421.cn/2025/2025-02-14-163225.jpeg

As you can see, the token type for identifiers is Identifier. So we just check whether the identifier name matches, and if it does, perform the replacement.

Be mindful of performance overhead during replacement.

Key Code

if (item.type === 'Identifier') {
      const {value} = item;
      let res = value;
      q?.forEach((obj) => {
        res = res.replace(obj.reg, `${obj.value}`);
      });
      if (value === res) return;
      source = source.replace(value, res);
    }

Final Thoughts

With auto-renaming supported, you can build other useful features—for example, keyword masking. For masking, you’d need to handle not just Identifier but also string literals.

References

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover