P
P
pegas2020-08-27 23:22:58
JavaScript
pegas, 2020-08-27 23:22:58

How to connect/use self-written babel-plugin?

I wrote a babel plugin that assigns the number 777 to all variables named test .

const babel = require('@babel/core');
  const code = `const test = 'text'`;

  const output = babel.transformSync(code, {
    plugins: [
      function myCustomPlugin() {
        return {
          visitor: {
            Identifier(path) {
              if (path.isIdentifier({ name: 'test' })) {
                path.parentPath.get('init').node.value = 777
              }
            },
          },
        };
      },
    ],
  });


Now the code string is code .

How can I include this babel plugin in webpack so that instead of the code line there is the code of a certain file, for example script.js ? For this plugin to work on a specific file

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-08-29
@bingo347

First of all. you need to issue it as a plugin:
https://github.com/jamiebuilds/babel-handbook/blob...

export default function({ types: t }) {
  return {
    visitor: {
      Identifier(path) {
        if(path.isIdentifier({ name: 'test' })) {
          path.parentPath.get('init').node.value = 777
        }
      }
    }
  };
};

Secondly, we make a babel config in js format, and write the absolute path to our plugin in the plugins section, path.join and __dirname to help

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question