'getting babel-node to work with yarn v2/3
I have a project with the following structure
./
├── README.md
├── babel.config.js
├── package.json
├── .yarnrc.yml
├── packages
│ ├── pkg-1
│ │ ├── babel.config.js
│ │ ├── index.js
│ │ └── package.json
│ └── pkg-2
│ ├── babel.config.js
│ ├── index.js
│ └── package.json
└── yarn.lock
pkg-2 has a dependency on pkg-1.
pkg-1/index.js looks like this
export function printName(){
console.log('my name');
}
console.log('print name')
pkg-2/index.js looks like this
import { printName } from "pkg-1";
printName()
// babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
pkg-2/package.json
{
"name": "pkg-2",
"packageManager": "[email protected]",
"scripts": {
"start": "babel-node index.js"
},
"dependencies": {
"pkg-1": "^1.0.0"
},
"devDependencies": {
"@babel/core": "^7.17.10",
"@babel/node": "^7.17.10",
"@babel/preset-env": "^7.17.10"
}
}
running the command yarn workspace pkg-1 run start
prints print name
as expected. However, running yarn workspace pkg-2 run start
results in the following
/Users/mds31/Documents/testing/yarn/packages/pkg-1/index.js:1
export function printName(){
^^^^^^
SyntaxError: Unexpected token 'export'
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1031:15)
at Module._compile (node:internal/modules/cjs/loader:1065:27)
at Module._compile (/Users/mds31/Documents/testing/yarn/.yarn/cache/pirates-npm-4.0.5-22f8e827ce-c9994e61b8.zip/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at require$$0.Module._extensions..js (/Users/mds31/Documents/testing/yarn/.pnp.cjs:13055:33)
at Object.newLoader [as .js] (/Users/mds31/Documents/testing/yarn/.yarn/cache/pirates-npm-4.0.5-22f8e827ce-c9994e61b8.zip/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.require$$0.Module._load (/Users/mds31/Documents/testing/yarn/.pnp.cjs:12895:14)
at Module.require (node:internal/modules/cjs/loader:1005:19)
presumably this is cos pkg-1 is not being compiled, is there a config setting that I'm missing?
Solution 1:[1]
Found a workaround to this that involves building all the packages before running with yarn node
. This is made a bit easier with this tool https://yarn.build/ which will run the build command of all workspaces.
script for running now looks like
{
"main": "dist/index.js",
"scripts": {
"build": "babel index.js --out-dir dist",
"start": "yarn build && yarn node dist/index.js"
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mike Davies |