Related
I don't understand what is wrong.
Node v5.6.0
NPM v3.10.6
The code:
function (exports, require, module, __filename, __dirname) {
import express from 'express'
};
The error:
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:140:18)
at node.js:1001:3
Node 13+ Since Node 13, you can use either the .mjs extension, or set {"type": "module"} in your package.json. You don't need to use the --experimental-modules flag. Modules is now marked as stable in node.js
Node 12 Since Node 12, you can use either the .mjs extension, or set "type": "module" in your package.json. And you need to run node with the --experimental-modules flag.
Node 9 In Node 9, it is enabled behind a flag, and uses the .mjs extension.
node --experimental-modules my-app.mjs
While import is indeed part of ES6, it is unfortunately not yet supported in NodeJS by default, and has only very recently landed support in browsers.
See browser compat table on MDN and this Node issue.
From James M Snell's Update on ES6 Modules in Node.js (February 2017):
Work is in progress but it is going to take some time — We’re currently looking at around a year at least.
Until support shows up natively (now marked stable in Node 13+), you'll have to continue using classic require statements:
const express = require("express");
If you really want to use new ES6/7 features in NodeJS, you can compile it using Babel. Here's an example server.
Unfortunately, Node.js doesn't support ES6's import yet.
To accomplish what you're trying to do (import the Express module), this code should suffice
var express = require("express");
Also, be sure you have Express installed by running
$ npm install express
See the Node.js Docs for more information about learning Node.js.
I'm shocked esm hasn't been mentioned. This small, but mighty package allows you to use either import or require.
Install esm in your project
$ npm install --save esm
Update your Node Start Script to use esm
node -r esm app.js
esm just works. I wasted a TON of time with .mjs and --experimental-modules only to find out a .mjs file cannot import a file that uses require or module.exports. This was a huge problem, whereas esm allows you to mix and match and it just figures it out... esm just works.
As mentioned in other answers Node JS currently doesn't support ES6 imports.
(As of now, read EDIT 2)
Enable ES6 imports in node js provides a solution to this issue. I have tried this and it worked for me.
Run the command:
npm install babel-register babel-preset-env --save-dev
Now you need to create a new file (config.js) and add the following code to it.
require('babel-register')({
presets: [ 'env' ]
})
// Import the rest of our application.
module.exports = require('./your_server_file.js')
Now you can write import statements without getting any errors.
Hope this helps.
EDIT:
You need to run the new file which you created with above code. In my case it was config.js. So I have to run:
node config.js
EDIT 2:
While experimenting, I found one easy solution to this issue.
Create .babelrc file in the root of your project.
Add following (and any other babel presets you need, can be added in this file):
{
"presets": ["env"]
}
Install babel-preset-env using command npm install babel-preset-env --save, and then install babel-cli using command npm install babel-cli -g --save
Now, go to the folder where your server or index file exists and run using:
babel-node fileName.js
Or you can run using npm start by adding following code to your package.json file:
"scripts": {
"start": "babel-node src/index.js"
}
Error: SyntaxError: Unexpected token import or SyntaxError: Unexpected token export
Solution: Change all your imports as example
const express = require('express');
const webpack = require('webpack');
const path = require('path');
const config = require('../webpack.config.dev');
const open = require('open');
And also change your export default = foo; to module.exports = foo;
In case that you still can't use "import" here is how I handled it:
Just translate it to a node friendly require. Example:
import { parse } from 'node-html-parser';
Is the same as:
const parse = require('node-html-parser').parse;
babel 7 proposal
can you add dev dependencies
npm i -D #babel/core #babel/preset-env #babel/register
and add a .babelrc in the root
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "current"
}
}
]
]
}
and add to the .js file
require("#babel/register")
or if you run it in the cli, you could use the require hook as -r #babel/register, ex.
$node -r #babel/register executeMyFileWithESModules.js
When I was started with express always wanted a solution to use import instead require
const express = require("express");
// to
import express from "express"
Many time go through this line:- Unfortunately, Node.js doesn't support ES6's import yet.
Now to help other I create new two solutions here
1) esm:-
The brilliantly simple, babel-less, bundle-less ECMAScript module loader.
let's make it work
yarn add esm / npm install esm
create start.js or use your namespace
require = require("esm")(module/*, options*/)
// Import the rest of our application.
module.exports = require('./src/server.js')
// where server.js is express server start file
Change in your package.josn pass path of start.js
"scripts": {
"start": "node start.js",
"start:dev": "nodemon start.js",
},
"dependencies": {
+ "esm": "^3.2.25",
},
"devDependencies": {
+ "nodemon": "^1.19.2"
}
2) Babel js:-
This can be divide into 2 part
a) Solution 1 thanks to timonweb.com
b) Solution 2
use Babel 6 (older version of babel-preset-stage-3 ^6.0)
create .babelrc file at your root folder
{
"presets": ["env", "stage-3"]
}
Install babel-preset-stage-3
yarn add babel-cli babel-polyfill babel-preset-env bable-preset-stage-3 nodemon --dev
Change in package.json
"scripts": {
+ "start:dev": "nodemon --exec babel-node -- ./src/index.js",
+ "start": "npm run build && node ./build/index.js",
+ "build": "npm run clean && babel src -d build -s --source-maps --copy-files",
+ "clean": "rm -rf build && mkdir build"
},
"devDependencies": {
+ "babel-cli": "^6.26.0",
+ "babel-polyfill": "^6.26.0",
+ "babel-preset-env": "^1.7.0",
+ "babel-preset-stage-3": "^6.24.1",
+ "nodemon": "^1.19.4"
},
Start your server
yarn start / npm start
Oooh no we create new problem
regeneratorRuntime.mark(function _callee(email, password) {
^
ReferenceError: regeneratorRuntime is not defined
This error only come when you use async/await in your code.
Then use polyfill that includes a custom regenerator runtime and core-js.
add on top of index.js
import "babel-polyfill"
This allow you to use async/await
use Babel 7
Need to upto date every thing in your project
let start with babel 7
.babelrc
{
"presets": ["#babel/preset-env"]
}
Some change in package.json
"scripts": {
+ "start:dev": "nodemon --exec babel-node -- ./src/index.js",
+ "start": "npm run build && node ./build/index.js",
+ "build": "npm run clean && babel src -d build -s --source-maps --copy-files",
+ "clean": "rm -rf build && mkdir build",
....
}
"devDependencies": {
+ "#babel/cli": "^7.0.0",
+ "#babel/core": "^7.6.4",
+ "#babel/node": "^7.0.0",
+ "#babel/polyfill": "^7.0.0",
+ "#babel/preset-env": "^7.0.0",
+ "nodemon": "^1.19.4"
....
}
and use import "#babel/polyfill" on start point
import "#babel/polyfill"
import express from 'express'
const app = express()
//GET request
app.get('/', async (req, res) {
// await operation
res.send('hello world')
})
app.listen(4000, () => console.log('🚀 Server listening on port 400!'))
Are you thinking why start:dev
Seriously. It is good question if you are new. Every change you are boar with start server every time
then use yarn start:dev as development server every change restart server automatically for more on nodemon
if you can use 'babel', try to add build scripts in package.json(--presets=es2015) as below. it make to precompile import code to es2015
"build": "babel server --out-dir build --presets=es2015 && webpack"
As of Node.js v12 (and this is probably fairly stable now, but still marked "experimental"), you have a couple of options for using ESM (ECMAScript Modules) in Node.js (for files, there's a third way for evaling strings), here's what the documentation says:
The --experimental-modules flag can be used to enable support for
ECMAScript modules (ES modules).
Once enabled, Node.js will treat the following as ES modules when passed to
node as the initial input, or when referenced by import statements within
ES module code:
Files ending in .mjs.
Files ending in .js, or extensionless files, when the nearest parent
package.json file contains a top-level field "type" with a value of
"module".
Strings passed in as an argument to --eval or --print, or piped to
node via STDIN, with the flag --input-type=module.
Node.js will treat as CommonJS all other forms of input, such as .js files
where the nearest parent package.json file contains no top-level "type"
field, or string input without the flag --input-type. This behavior is to
preserve backward compatibility. However, now that Node.js supports both
CommonJS and ES modules, it is best to be explicit whenever possible. Node.js
will treat the following as CommonJS when passed to node as the initial input,
or when referenced by import statements within ES module code:
Files ending in .cjs.
Files ending in .js, or extensionless files, when the nearest parent
package.json file contains a top-level field "type" with a value of
"commonjs".
Strings passed in as an argument to --eval or --print, or piped to
node via STDIN, with the flag --input-type=commonjs.
I'm going to address another problem within the original question that no one else has. After recently converting from CommonJS to ESM in my own NodeJS project, I've seen very little discussion about the fact that you cannot place imports wherever you want, like you could with require. My project is working great with imports now, but when I use the code in the question, I first get an error for not having a named function. After naming the function, I receive the following...
import express from 'express'
^^^^^^^
SyntaxError: Unexpected identifier
at Loader.moduleStrategy (internal/modules/esm/translators.js:88:18)
You cannot place imports inside functions like you could require. They have to be placed at the top of the file, outside code blocks. I wasted quite a bit of time on this issue myself.
So while all of the above answers are great at helping you get imports to work in your project, none address the fact that the code in the original question cannot work as written.
import statements are supported in the stable release of Node since version 14.x LTS.
All you need to do is specify "type": "module" in package.json.
In my case it was looking after .babelrc file, and it should contain something like this:
{
"presets": ["es2015-node5", "stage-3"],
"plugins": []
}
My project uses node v10.21.0, which still does not support ES6 import keyword. There are multiple ways to make node recognize import, one of them is to start node with node --experimental-modules index.mjs (The mjs extension is already covered in one of the answers here). But, this way, you will not be able to use node specific keyword like require in your code. If there is need to use both nodejs's require keyword along with ES6's import, then the way out is to use the esm npm package. After adding esm package as a dependency, node needs to be started with a special configuration like: node -r esm index.js
I've been trying to get this working. Here's what works:
Use a recent node version. I'm using v14.15.5. Verify your version by running: node --version
Name the files so that they all end with .mjs rather than .js
Example:
mod.mjs
export const STR = 'Hello World'
test.mjs
import {STR} from './mod.mjs'
console.log(STR)
Run: node test.mjs
You should see "Hello World".
Simply install a higher version of Node. As till Node v10 es6 is not supported. You need to disable a few flags or use
I am pretty new to vue.js - I only started using it today and naturally I have run into an error I cannot seem to resolve.
I am using the v-md-date-range-picker module:
(https://ly525.github.io/material-vue-daterange-picker/#quick-start.
The instructions tell me to do the following:
1
npm install --save v-md-date-range-picker
2
<template>
<v-md-date-range-picker></v-md-date-range-picker>
</template>
3
<script>
import Vue from 'vue';
import VMdDateRangePicker from "v-md-date-range-picker";
import "v-md-date-range-picker/dist/v-md-date-range-picker.css";
Vue.use(VMdDateRangePicker);
</script>
So, I ran the command in terminal in my project folder, added the 2 bit of code to my HelloWorld.vue page and then added the code from step 3 into the main.js.
When I have a look in my package.json file, I see:
"dependencies": {
"core-js": "^2.6.5",
"v-md-date-range-picker": "^2.6.0",
"vue": "^2.6.10"
},
However, I get the error:
Module not found: Error: Can't resolve 'v-md-date-range-picker/dist/v-md-date-range-picker.css' in '/Users/James/Documents/projects/vue-test/src'
am I missing something blatantly obvious here?
Edit:
I tried the response in the comments below which did not work.
On the main page of the module, I followed the instructions. However, going through the pages I found the same instructions with some extra text:
I assume that you have a working bundler setup e.g. generated by the vue-cli thats capable of loading SASS stylesheets and Vue.js SFC (Single File Components).
I am going to go out on a limb here and say I do not have a working bundler. I went into the node_modules folder, found that module and looked inside. There was no dist folder. Just .scss files etc..
So, I assume that I somehow need to build this project first.
How do I do that?
I thought running it in the browser would have done this on the fly but it clearly has not.
Edit 2:
After some googling around I found the command:
$ npm run build.
Which gives me this error:
This dependency is not found, To install it, you can run: npm install --save v-md-date-range-picker/dist/v-md-date-range-picker.css
So, I run that command and then I get the error:
Could not install from "v-md-date-range-picker/dist/v-md-date-range-picker.css" as it does not contain a package.json file.
Check if you can find this in the webpack.base.conf.js inside the build folder. If not add it.
module: {
rules: [
{
test: /\.css$/,
loader: ['style-loader', 'css-loader'], // Note that the order is very important
},
Run npm install style-loader css-loader --save before adding it to the file if it isn't there.
To Address your question
Run the command: npm install sass-loader --save
Then add an import for every SCSS file in the module.
This is not the most optimal solution, but that package looks broken to me and this is merely a workaround.
I will take time to try out the library myself and try to provide a fix for it.
Create v-md-date-range-picker.css in v-md-date-range-picker/dist/ and copy css from
md-date-range-picker.min.css
and refresh your page. For some reason css file is not being created when we install md-date-range-picker.min
I have created a React component inside a project that I'd like to use in multiple projects. At the moment, I only care about doing this locally and for development. The React Component is rendered into the root div, the project uses webpack and babel to transpile JSX, ES6 and some ES7 features into a bundle.
I thought it would be simple to export this component such that I can simply run npm install MyComponent and begin using it in a fresh project. However, I find it isn't so straight forward. In particular, I've been reading for hours and hours and only seem to be getting more confused.
If my end goal is to keep developing 'MyComponent' in its containing project, while using 'MyComponent' in any number of other local projects, what are my options? The first thing I did was change the main key of my package.json to /src/components/MyComponent and run npm pack. This produces a tgz file I can install via its absolute filepath in other projects. However, I found that the es6 and jsx was not being transpiled and so my client projects would be unable to parse MyComponent. I then used webpack to transpile into lib/MyComponent, but when I have import MyComponent from './path/to/MyComponent-1.0.0.tgz I'd only see {} (an empty object) in the console.
Searching for solutions to my problem turn up many different approaches pulling together NPM, Grunt, Gulp, Babel, Webpack, etc.. And I am worried it will be many many more hours (days?) before I can grind that down to something understandable.
Given my requirements, what is the simplest solution I can implement to 1) compile down my React Component to the simplest to import module 2) import it into any local projects 3) continue to develop the package in the original host project and have changes easily propagate to client projects.
In general, if you're going to begin creating React components as separated packages (which is a great pattern, for all the reasons you've already mentioned) - you're going to need to get at least a bit familiar with webpack and babel. There's a ton to learn here, but let me try to point you in the right direction:
// webpack.config.js
/* eslint-disable */
const path = require('path')
const webpack = require('webpack')
const ENVIRONMENT = process.env.NODE_ENV
const PRODUCTION = ENVIRONMENT === 'production'
const SOURCEMAP = !PRODUCTION || process.env.SOURCEMAP
const library = 'your-lib-name' // << RENAME THIS <<
const filename = PRODUCTION ? `${library}.min.js` : `${library}.js`
const plugins = []
if (PRODUCTION) {
plugins.push(
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(ENVIRONMENT),
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
output: { comments: false, semicolons: false },
sourceMap: SOURCEMAP,
})
)
}
module.exports = {
devtool: SOURCEMAP ? 'source-map' : 'none',
entry: `${__dirname}/path/to/your/component.js`, // << RENAME THIS <<
externals: {
'react': 'react',
'react-dom': 'react-dom',
},
module: {
loaders: [{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
}],
},
output: {
filename,
library,
path: `${__dirname}/lib`,
libraryTarget: 'umd',
umdNamedDefine: true,
},
plugins,
}
I know that looks like a bunch - but it handles the majority of what you're going to want. In specific:
If you specify NODE_ENV=production when building, this will uglify/minify your package, and do some other trimming which you may want later.
Building with this script will output a sourcemap, which you can use with dev tools to inspect your minified code in the debugger window, among other things.
This marks react and react-dom as externals - which means they won't get bundled up and packaged inside your bundle. This is great - because it means you won't get 2+ copies of react's filesize just because you've imported your own component!
To use it, though, you now need some package.json love.
package.json
{
"name": "Your Name",
"version": "0.0.1",
"description": "This is my awesome react package!",
"main": "path/to/your/component.js",
"author": "Your Name",
"license": "MIT",
"repository": { /* Your Repo Info Here */ },
"dependencies": {
"any-packages-you-need-included-in-builds": "^1.0.0"
},
"devDependencies": {
"babel-cli": "^6.22.2",
"babel-loader": "^7.1.0",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.22.0",
"prop-types": "^15.5.10",
"react-dom": "^15.6.1",
"webpack": "^3.0.0"
},
"scripts": {
"build": "yarn prebuild && NODE_ENV=production webpack",
"prebuild": "mkdir -p ./lib && rm -rf ./lib/*"
}
}
Obviously, you can have a lot more here if you need it - such as other babel-plugin-* plugins that you use in your transpilation, other packages, etc.But this set will let your webpack build run. Note that the scripts here assume you're using yarn - so that you can run yarn build, and that you're on a posix system, for mkdir to work. If you're on windows or not using yarn, just update the scripts accordingly.
The rest is just learning to publish your package to npm or another package repository. Primarily, that's just setting the version number in package.json to something new (npm version) and then publishing (npm publish). You will have to have an npm account for this, of course - and be logged in (npm login).
Once you've published to npm you can just yarn add your-package-name.
Remember, though - we marked react and react-dom as external - so in the consuming package, you'll need to make sure they're available as window.React and window.ReactDOM - or you'll need to include the component directly from node_modules/your-package-name/path/to/your/component.js
You don't need to npm pack a package to use it. If you make your component into a git repo and put it on Github, you can use NPM to install it directly from Github by using npm install alex/mycomponent where alex is your github username and mycomponent is the repo name. Re-running that command will re-install from Github, in case you make changes to the repo.
Once you're happy with the component, you can upload it to the NPM registry to install like any other package (npm install name). Using Github at first makes it a bit easier to develop.
Webpack might not compile things from node_modules by default. Usually, packages are pre-compiled before being published anyway, but you should be able to configure webpack to build your 'packaged' component, along with the rest of your app. Maybe this will help: https://stackoverflow.com/a/38008149/7486612
In order to push react libraries into NPM, you may need some boilerplate which will install and convert many things for you (and you can still use your current react module as the main source, just follow the guides at the end of my answer, then you will surely get all the ideas)
Or you can also refer to my previous answer to a similar question:
Issue with publishing to npm
=====
I've also pushed several react libraries successfully into NPM:
https://www.npmjs.com/~thinhvo0108
=====
Your github repositories' folder structure should also look like mine:
https://github.com/thinhvo0108/react-paypal-express-checkout
=====
Useful tutorial below here:
(boilerplate source) https://github.com/juliancwirko/react-npm-boilerplate
(author's article) http://julian.io/creating-react-npm-packages-with-es2015/
Start by looking at existing component library, eg Material UI.
Specifically check out npm scripts they have (see package.json):
"build:es2015": "cross-env NODE_ENV=production babel ./src --ignore *.spec.js --out-dir ./build",
"build:es2015modules": "cross-env NODE_ENV=production BABEL_ENV=modules babel ./src/index.js --out-file ./build/index.es.js",
"build:copy-files": "babel-node ./scripts/copy-files.js",
"build:umd:dev": "webpack --config scripts/umd.webpack.config.js",
"build:umd:prod": "cross-env NODE_ENV=production webpack --config scripts/umd.webpack.config.js",
"build": "npm run build:es2015 && npm run build:es2015modules && npm run build:copy-files && npm run build:umd:dev && npm run build:umd:prod",
That's example of very involved and high quality component library, that makes sure that regardless of your build pipeline you'll be able to use it.
Setting up build process with webpack might be cumbersome, but don't concentrate on that too much from the begining, and cover cases that are most straight forward to you.
Also check out https://storybook.js.org/ while working on your components.
I created a React Native component which lives in a different folder with its own package.json file, and I want to use it in another project
MyComponent is located in Workspace/MyComponent and as a few dependencies in package.json
"dependencies": {
"react-navigation": "^1.0.0-beta.11"
},
"peerDependencies": {
"react": "16.0.0-alpha.12",
"react-native": "0.45.1"
},
"devDependencies": {
"react": "16.0.0-alpha.12",
"react-native": "0.45.1"
}
I am currently in the development of MyComponent so I have run npm install in the repo, there is a node_modules folder.
My have linked MyComponent with MyApp which is located in Workspace/MyApp, using npm link
Although, when I run MyApp and try to use MyComponent, it complains about duplicated declaration, because react is in both MyComponent and MyApp, and they are linked.
If I remove the node_modules folder from MyComponent, react-navigation complains about react not defined.
In the ReactJS world, webpack for example allow to set the root with the preferred node_modules folder which is great.
module.exports = {
...
resolve: {
root: path.resolve(__dirname, 'node_modules'),
}
...
}
I wish to do something similar so I don't have duplicated modules and can debug MyComponent in MyApp locally without reinstalling MyComponent for every single change. What is the best approach for me to achieve this?
Thanks
I found a solution to my question, and it's called whackage
https://github.com/FormidableLabs/whackage
If this is something that will eventually be put in its own repo and then will be installed like any other component, I would probably just build it in the node_modules directory of the parent project. That would prevent you from having to run npm install for every little change.
You can also declare a dependency on a local file and then npm will install it in node_modules
"dependencies": {
"my-component": "file:app/components/my-component",
}
So I have a component that I've built within my project that is referenced in my package.json file. When I run npm install this component is installed in the node_modules folder. That could help with the duplicate library declarations but it wouldn't solve the repeated use of npm install
Update: I just learned that npm 5 doesn't copy the files over to the node_modules folder. It now creates a symlink (basically, a virtual directory that points to the real one) to the code in your project.
This means you will not have to run npm install each time you change your code so it will likely be the best solution for you.
I'm trying to use React.js on Ubuntu for a web dev project, but I can't figure out how to set it up. Please note that I am a beginner, and have only used Javascript with JQuery before. I tried to follow the instructions here, and I think I made it up to the point where I'm supposed to configure Babel. Here, in the terminal I ran
npm install --save-dev babel-cli babel-preset-react babel-preset-es2015
echo '{ "presets": ["react", "es2015"] }' > .babelrc
echo 'console.log([1, 2, 3].map(n => n + 1))' > index.js
./node_modules/.bin/babel index.js
The output I get is:
"use strict";
console.log([1, 2, 3].map(function (n) {
return n + 1;
}));
This is great and all, but I want to be able to run an html file with a corresponding .js file, as I would normally. As it is, when I write something like
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
with a corresponding html file, I just get console errors (Unexpected Token insert or something). Obviously, I haven't managed to install Ecmascript/JSX or whatever, and I don't really know what I'm doing.
So, I guess my question is, can anyone help me with a detailed explanation of how to get started? I just want to be able to write Javascript with React, and create a simple webpage. Thank you!
You dont need lots of stuff to start with React.
All you need to use react is include react and reactdom. Thats' it.
ReactDOM.render(
React.createElement('h1', {}, "Hi! This is the simplest way to get started with ReactJS"),
document.getElementById('only-react')
);
<script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
<script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>
<div id="only-react"></div>
These lines should get you started with just React without all the bloatware you will find in most of the tutorials.
Installing React
To install React with npm, run:
npm init
npm install --save react react-dom
Creating a Single Page Application
npm install -g create-react-app
create-react-app hello-world
cd hello-world
npm start
create-react-app
IMO, the best way to start a React project for a beginner is to use create-react-app. It is a zero config package that lets you jumpstart your React development. It contains necessary packages needed for react development.
npm install -g create-react-app
create-react-app react-app
cd react-app
npm start
React Environment Using webpack and Babel
If you don't want that and want to setup your own React project you could configure one with babel and webpack. I do recommend that you check this out to learn. Here's a tutorial.
For a beginner I'd recommend the first approach.
Your error come from here:
echo '{ "presets": ["react", "es2015"] }' > .babelrc
babel applies presets from right to left: it should transpile jsx first then the es2015 code.
The solution is to modify your .babelrc file by switching the order in the presets array like this:
{ "presets": ["es2015", "react"] }
Otherwise create-react-app is the best solution to begin without any configuration.
you have to install babel-cli globally so u can access babel command from anywhere. looks like you already installed babel-preset-react and babel-preset-env.
create a public folder and src folder. in public folder add index.html and index.js.
index.html
<body>
<div id="here"></div>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="./index.js"></script>
index.js should be empty. Whole point is to create a file that we change and we r going to have another file,index.js, that get generated or compiled by babel. index.js will be an auto-generated file.
In src folder we r gonna use react.jsx. create app.js in src folder. for the demonstration enter this simple code :
src/app.js
const template = <p>this is jsx</p>;
const appRoot = document.getElementById("here");
ReactDOM.render(template2, appRoot);
now run this command in terminal:
babel src/app.js --out-file=public/index.js --presets=env,react --watch
now check public/index.js. you should have this:
"use strict";
var template = React.createElement(
"p",
null,
"this is jsx"
);
var appRoot = document.getElementById("here");
ReactDOM.render(template2, appRoot);