0

I'm currently writing a babel plugin.

I have a folder called plugin a package.json and the following file:

// index.js
import template from "@babel/template";

module.exports = function(babel) {
  // some code
}

Then I have a folder called test-plugin. It also has a package.json and the following babel.config.json:

{
  "plugins": ["../plugin"]
}

When I run ./node_modules/.bin/babel test.js, I get the following error:

import template from "@babel/template";
^^^^^^

SyntaxError: Cannot use import statement outside a module

So, I add "type": "module" to plugin/package.json and try again. This time I get this error:

Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import 'path/to/plugin' is not supported resolving ES modules imported from path/to/test-plugin/node_modules/.pnpm/@babel+core@7.18.10/node_modules/@babel/core/lib/config/files/import.cjs
Did you mean to import path/to/plugin/index.js?

So in babel.conifg.json, I try the following:

{
  "plugins": ["../plugin/index.js"]
}

Now I get this error:

ReferenceError: [BABEL]: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/path/to/plugin/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension. (While processing: /path/to/plugin/index.js)

Now I still don't know how to resolve the original error? Any help would be much appreciated.

Jomy
  • 514
  • 6
  • 22
  • did you try using `const template = require("@babel/template");` in index.js – Anand Bhushan Aug 18 '22 at 05:23
  • @AnandBhushan If I do that, it does compile, but when I try using the imported function `template`, it gives me a runtime error: TypeError: path/to/plugin-test/test.js: template is not a function – Jomy Aug 18 '22 at 08:48

0 Answers0