Error: Couldn't find preset "react" when installed using npm install --global babel-preset-react but works without global flag - node.js

I installed Babel CLI (version 6) using npm install --global babel-cli. I then install react preset using npm install --global babel-preset-react.
I then setup the .babelrc file in the project directory to
{
"presets": ["react"]
}
When I try to build a JSX file it fails with
Error: Couldn't find preset "react"
at OptionManager.mergePresets (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:310:17)
at OptionManager.mergeOptions (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:270:12)
at OptionManager.addConfig (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:206:10)
at OptionManager.findConfigs (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:347:16)
at OptionManager.init (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:392:12)
at File.initOptions (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/index.js:191:75)
at new File (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/index.js:122:22)
at Pipeline.transform (/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/pipeline.js:42:16)
at transform (/usr/local/lib/node_modules/babel-cli/lib/babel/util.js:53:22)
at Object.compile (/usr/local/lib/node_modules/babel-cli/lib/babel/util.js:62:12)
If I install the preset without --global flag (i.e. installs in node_modules/ folder locally) then the build works. How do i set up to get babel to work with a global preset?

You can specify the absolute (or relative) path to the preset you are trying to use, e.g:
babel --presets /usr/local/lib/node_modules/babel-preset-react --watch jsx/ --out-dir js/

Optional Fix
You can do it this way. Write these lines in your prompt. Now the only thing is with global you might have to use the fix suggested above by #Petar
which is
babel --presets /usr/local/lib/node_modules/babel-preset-react --watch jsx/ --out-dir js/
but this one does all you need.
npm i babel-cli babel-preset-react
babel --presets react jsx/ --watch --out-dir js/
and Then optionally add a .gitignore file in your github repo with content = node_modules/
now run your jsx transformation with the same command.

Related

What packages do I need to install to accomplish a "vue build <src path> --config <config file path> --dist <dist location> --prod --lib" command?

I've forked an old Vue.js package that has some issues in it (v-money) and made the necessary changes to accomplish what I need. But now when I try to build using the package's original method, I'm getting an error:
npm run build
vue build ./src/index.js --config ./build.config.js --dist ./dist/ --prod --lib "--disable-compress"
Usage: vue build [options]
alias of "npm run build" in the current project
Options:
-h, --help display help for command
Unknown option --config.
I'm guessing I've got the wrong version of Vue.js installed, as the package didn't indicate what version it's supposed to be, but I can't find anything on the web that shows --config, --dist, --prod, and --lib as build options for Vue.js.
I've attempted to build the package as-is without any of my small changes and that fails in the same way.
Install the following dev dependencies from the root of the v-money project:
npm i -D vue-cli#2.8.2 \
uglify-es \
uglifyjs-webpack-plugin#^1
Edit build.config.js to use the Uglify dependencies installed above:
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
webpack: {
⋮
plugins: [
new UglifyJSPlugin(),
⋮
]
}
}
demo

Using Node.js with Flow in WebStorm

I am trying to setup WebStorm with Flow typing for a Node.js project.
I have it all working fine with NPM scripts but would like to integrate with the IDE.
Here is the scripts portion of my package.json:
"scripts": {
"dev":
"watch --wait=1 'flow-remove-types src/ -d lib/ --all --pretty' ./src/ & nodemon ./lib/server.js",
"start": "npm run flow:build && node ./lib/",
"lint": "eslint src/**",
"test": "npm run flow:build && jest lib",
"coverage": "jest --collectCoverageFrom=src/**.js --coverage src",
"flow": "flow",
"flow:check": "flow check ./src/",
"flow:build": "flow-remove-types ./src/ -d ./lib/ --all --pretty",
"flow:deps": "flow-typed install",
"flow:watch": "flow-watch"
},
Now if I modify the run configuration for a test and:
change the src directory to lib
specify a before launch, run NPM script 'flow:build'
then I can run that configuration.
I still have two problems.
Debugging will not stop on a breakpoint
If I hit the arrow in the source code gutter to run the test, it creates a new config which runs against the flow source and fails
Does anyone have Node.js and flow working well together in WebStorm?
You can use --sourcemaps and -pretty flags:
flow-remove-types --pretty --sourcemaps --out-dir out/ in/
The -m or --sourcemaps flag adds sourcemaps files to your /out folder
The -p or --pretty flag removes the empty spaces in the files of your /out folder
flow-remove-types does not generate sourcemaps, so there is absolutely no way for debugger to map the generated file in lib to original files in src. You have to add breakpoints to the generated files located in lib folder if you like to debug your tests
no way - configuration is generated for the file you hit the arrow in. If you like to run individual tests from gutter, hit the arrow in generated file, not in the source one
You can use Babel flow preset instead of flow-remove-types:
npm install --save-dev babel-cli babel-preset-env babel-preset-flow
create a .babelrc file in your project root dir:
{
"presets": ["flow"]
}
And that's all you have to do - no precompiling, etc., running from gutter/debugging for source files will work out of the box

How to make babel transpile modules linked using "npm link"

I have a lot of code in my currently project(my-project) that will be needed in a new one. This code has been written in ES6 and transpiled after with babel.
I've created a module called "my-module" with this shared code and linked it to "my-project" using npm link
The problem is that when I start the project, the code from "my-module" is not beening tranpiled and throws an error right at the import statement.
The code inside my-module will be edited a lot. How to make it works?
package.json
"scripts": {
"start": "nodemon bin/dev",
"clean": "rm -rf dist",
"build": "yarn run clean && mkdir dist && babel src -s -d dist",
"production": "yarn run build && node bin/production"
},
.babelrc
{
"presets": ["es2015", "stage-2"]
}
The linked project will not find your .babelrc file. You have a few options:
Place a .babelrc in my-project or a higher level directory. This will require the babel plugins to be installed in that module though (or globally)
If you're using a build tool (i.e. webpack, browserify, etc.) you can declare the babel config there.
This comment helped me out: https://github.com/babel/gulp-babel/issues/93#issuecomment-249172581
My project uses browserify, so declaring the same plugins in the build script that are in .babelrc and invoking require.resolve caused the npm linked project to be transpiled correctly.
return browserify.transform('babelify', {
sourceMaps: true,
global:true,
plugins: ['babel-preset-es2015'].map(require.resolve)
})

Transform JSX to JS using babel

I'm new to babel and I'm trying to convert my main.jsx file to main.js. I installed the following babel plugin.
npm install --save-dev babel-plugin-transform-react-jsx
Created a file called .babelrc in the application root directory.
{
"plugins": ["transform-react-jsx"]
}
My app is using the express server, so on running node app.js I was expecting the babel to transform main.jsx to main.js but nothing happens.
Can any one point out what I'm doing wrong ?
if you are only using babel to transform jsx to js, this is what you need :
installation
install babel-cli as global (optional) sudo npm install -g babel-cli
install babel-preset-es2015 (optional. if your code using es6 standard) npm install babel-preset-es2015
install babel-preset-react (required)
configuration
in your root of project, add this file .babelrc and write this to it
{
"presets": ["es2015", "react"]
}
or
{
"presets": ["react"]
}
run
babel source_dir -d target_dir
Just follow the instructions at https://www.npmjs.com/package/babel-plugin-transform-react-jsx
First, create a new folder, test, and from the folder init a new project:
npm init
Install babel CLI
npm install --save-dev babel-cli
Then install babel-plugin-transform-react-jsx
npm i babel-plugin-transform-react-jsx
In the test folder create a sample jsx file index.jsx
var profile = <div>
<img src="avatar.png" className="profile" />
<h3>{[user.firstName, user.lastName].join(' ')}</h3>
</div>;
And finally, run the transofmation command in you terminal from the test folder:
.\node_modules\.bin\babel --plugins transform-react-jsx index.jsx
You'll see the output in you terminal window.
You can configure webpack and use babel as a loader to transpile your jsx
var webpack = require('webpack');
var path = require('path');
module.exports ={
context: path.join(__dirname, "src"),
devtool: "inline-sourcemap",
entry: "./main.js",
module: {
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015','stage-0'],
}
}
]
},
output: {
path: __dirname+ "/src",
filename: "client.min.js"
}
}
Tutorials
As of 2023 if you are using babel to transform jsx to js, this is what you will need to do:
Install Packages
Install the following globally on your machine:
npm install -g #babel/cli
npm install -g #babel/core
npm install -g #babel/preset-react
or install the following as a project dependency (my personal preference):
npm install --save-dev #babel/cli
npm install --save-dev #babel/core
npm install --save-dev #babel/preset-react
Create Configuration File
Create a .babelrc config file at the root of your project with the following setting as a bare minimum:
{
"presets": ["#babel/preset-react"]
}
You should review the babel docs if you have a more complicated use case and determine what additional settings you may need to add. You can find the settings for compiling jsx to js on the #babel/preset-react page.
Compile
You can compile any jsx file into js by running the following command in your terminal:
npx babel [jsx-file-here.jsx] -d [output-directory]
If your jsx file imports anything please keep the following in mind:
This will not import any imported code. You will need to also compile any files that are imported. You can then use your code as a browser module: see next 2 points.
JS imports are widely supported now (see also) but you will need to add type="module" to the script tag in your HTML.
Remember you must include the file extension .js in your import statements still! No browser will intuptret import Foo from './bar' as import Foo from './bar.js.
If you do not want to do the previous you can use something like rollup.js to bundle all the files into a single script.

Node error: SyntaxError: Unexpected token import

I don't understand what is wrong. I checked other forum talking about transpilation and babel. What do I have to do?
node -v
v5.5.0
my code:
import recast from 'recastai'
and the error
(function (exports, require, module, __filename, __dirname) { import recast from 'module1'
^^^^^^
SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:139:18)
at node.js:999:3
ES6 imports are a recently introduced feature and the current stable version of Node does not support them yet. Node.js issue tracker has an open issue for this - but until V8 and Node add support for this feature, you will need to use a transpiler (most popular one being babel) to be able to use imports.
For quickly trying out transpilation, babel provides a web based REPL. This one demonstrates your code being transpiled.
The babel project homepage points to the relevant resources for getting started with Babel and integrating it with your development workflow.
For the simplest setup, visit this setup page and select CLI in the Babel built-ins section.
This basically involves three simple steps:
Install babel-cli : npm install --save-dev babel-cli babel-preset-es2015
Create .babelrc configuration file: echo '{ "presets": ["es2015"] }' > .babelrc
Use the installed module to transpile your source code: ./node_modules/.bin/babel src -d lib
The aforementioned setup page also illustrates how to add an npm script to simplify the last step. Alternatively you can integrate babel with your editor or build chain so that your files are automatically compiled on change.
In case you don't want to deal with babel. This one worked for me.
const calc = require('./my_calc');
let {add, multiply} = calc;
1) Install the latest presets
yarn add --dev babel-preset-latest
2) Create .babelrc and add the following
{
"presets": ["latest"]
}
3) Run your script
npx babel-node yourscript.js
Or in your package.json file add
"scripts": {
"start": "babel-node index.js"
}
Getting Started
First we'll install babel-cli.
$ npm install --save-dev babel-cli
Along with some presets.
$ npm install --save-dev babel-preset-es2015 babel-preset-stage-2
package.json:
"scripts": {
"start": "babel-node index.js --presets es2015,stage-2"
}
run:
$ npm start
Watching file changes with nodemon:
We can improve our npm start script with nodemon.
$ npm install --save-dev nodemon
Then we can update our npm start script.
package.json:
"scripts": {
"start": "nodemon index.js --exec babel-node --presets es2015,stage-2"
}
run:
$ npm start
If you are using pm2, then follow these steps:
$ pm2 start app.js --interpreter babel-node
Its very simple to resolve this issue, import is ES6 syntax and Node has difficulty in supporting it, you need to add Babel as a transpiler, go to package.json and add the following
First add a script tag to use babel while running the JS code for transpiling.
"scripts": {
"start": "nodemon ./app.js --exec babel-node -e js"
}
And then add the following as the Babel devDependencies
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1"
}
after this you also need to configure the babel presets file, therefore create .babelrc file at the root directory and define the presets as follows
{
"presets": [
"es2015",
"stage-0"
]
}
Don't forget to do an npm install in the end
Thanks to a NodeJS enhancement proposal we have a path forward. You can use #standard-things/esm
Find the announcement here Simply run
npm i --save #std/esm
In your packaged today.

Resources