I'm struggling to get my jsx files compiled using babel + presets. My project structure is a bit non-standard as js/jsx files are placed in a sibling directory of the config/build files:
.
├── frontend_config
│ ├── node_modules
│ │ ├── babel-cli
│ │ ├── babel-core
| | | ...
│ ├── package-lock.json
│ └── package.json
├── jsx
│ ├── foo
│ │ ├── Bar.jsx
...
I've narrowed down the issue to the minimal by trying to run babel from the terminal, inside the frontend_config
directory I run:
npx babel ../jsx/foo/Bar.jsx --presets=env,react
Couldn't find preset "env" relative to directory "../jsx/foo"
I've installed both babel-preset-env
and babel-preset-react
but I don't know how to tell babel where are they placed. I've also tried using a .babelrc
file but the behavior is the same.
My setup is:
$ npx babel --version
6.26.0 (babel-core 6.26.0)
$ node --version
v8.9.4
You have installed babel dependencies like cli, presets, plugins in frontend_config folder and you're transpiling JSX files which are not placed in same root babel installed. That is why, it shows like Couldn't find preset "env" relative to directory
do like below in your webpack/grunt/.babelrc :
use absolute paths
or use require like below :
var babelenv = require('babel-preset-env');
var babelreact = require('babel-preset-react');
var babelamd = require('babel-plugin-transform-es2015-modules-amd');
and presets: [ babelenv, babelreact],plugins : [ babelamd ]
Hope it helps.
run npm install @babel/preset-env --save-dev
More info @ https://babeljs.io/
For anyone having this issue, the solution when using Babel 6 and placing node_modules
in a different directory than the project root is to use absolute paths . Hence the babel call would look like:
npx babel ../jsx/foo/Bar.jsx --presets /Users/foo/bar/frontend_config/node_modules/babel-preset-env/,/Users/foo/bar/frontend_config/node_modules/babel-preset-react/
Credit to the answer goes to loganfsmyth
You can also just put this in your .babelrc file if you like
{
"presets" : [ "/Users/foo/bar/frontend_config/node_modules/babel-preset-env" ]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.