I am starting a Node.js project that uses react-pdf. This means that I need Babel to transpile the TSX syntax into JS code. I am having big trouble to make it work properly. If I want to use import/export
syntax, my package.json
must say that "type": "commonjs"
. But, as far as I'm aware, if I want to use top-level await type
property must be set to "module"
. I don't really know what is the difference between both.
So, I set "type": "commonjs"
, I receive the following error:
const token = await getAuthToken();
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
And now, when "type": "module"
:
var _react = _interopRequireDefault(require("react"));
^
ReferenceError: require is not defined in ES module scope, you can use import instead
I can see that the transpiled files use require()
syntax, which is not allowed when type is set to "module". So, isn't there any way to make Babel transpile to import/export
syntax, so I can both use this syntax AND top-level await feature?
[EDIT]: As asked, there goes my .babelrc configuration file:
{
"presets": [
[
"@babel/env",
{ "targets": { "node": 18 } }
],
[
"@babel/preset-react",
{ "targets": { "node": 18 } }
],
[
"@babel/preset-typescript",
{ "targets": { "node": 18 } }
]
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-object-rest-spread"
]
}
If it's important, my package.json
script line is:
"run": "babel --extensions .ts,.tsx src -d output && node output/document.js"