Webpack Plugin to Auto-Rename Variables

· 1 min read · 200 Words · -Views -Comments

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