How to compile JSX with Babel into JavaScript - node.js

I'm trying to compile the very simplest React tutorial using browserify. I've run:
sudo npm install browserify
Then as stated here http://babeljs.io/docs/setup/#browserify
sudo npm install --save-dev babelify
Then I have my file js/script.jsx
var HelloMessage = React.createClass({
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
ReactDOM.render(<HelloMessage name="John" />, mountNode);
And I'm running from the folder
browserify js/script.jsx -t babelify --outfile bundle.js
But then this happens:
djave at djaves-iMac-3 in /Volumes/djave/react
$ browserify js/script.jsx -t babelify --outfile bundle.js
SyntaxError: /Volumes/djave/react/js/script.jsx: Unexpected token (4:11)
2 | var HelloMessage = React.createClass({
3 | render: function() {
> 4 | return <div>Hello {this.props.name}</div>;
| ^
5 | }
6 | });
7 |
What am I doing wrong? This is literally my first step into this area so it may be I've missed a pretty major step.
More errors (although I suspect this won't help too much!)
at Parser.pp.raise (/Volumes/djave/react/node_modules/babelify/node_modules/babel-core/node_modules/babylon/index.js:1425:13)
at Parser.pp.unexpected (/Volumes/djave/react/node_modules/babelify/node_modules/babel-core/node_modules/babylon/index.js:2907:8)
at Parser.pp.parseExprAtom (/Volumes/djave/react/node_modules/babelify/node_modules/babel-core/node_modules/babylon/index.js:754:12)
at Parser.pp.parseExprSubscripts (/Volumes/djave/react/node_modules/babelify/node_modules/babel-core/node_modules/babylon/index.js:509:19)
at Parser.pp.parseMaybeUnary (/Volumes/djave/react/node_modules/babelify/node_modules/babel-core/node_modules/babylon/index.js:489:19)
at Parser.pp.parseExprOps (/Volumes/djave/react/node_modules/babelify/node_modules/babel-core/node_modules/babylon/index.js:420:19)

All fixed, thanks to #azium.
First get the React preset: http://babeljs.io/docs/plugins/preset-react/
npm install babel-preset-react
Next, create a file called .babelrc in the root of your project, and put in it the following:
{
"presets": ["react"]
}
Then do the
browserify js/script.jsx -t babelify --outfile bundle.js
That compiles everything, and as an extra to make sure that react and react-dom are included (as shown here) you can run the following:
sudo npm install --save react react-dom

Related

Cannot find module 'react' from 'index.js' - (node_modules/jest-resolve/build/index.js:259:17)

My project creation process (this is a create-react-app typescript version template:
25 npx create-react-app test --template typescript
26 cd test
27 ls
28 npm install --save-dev react-test-renderer
29 npm test
30 npm test
31 node --version
32 npx create-react-app --version
33 npm install antd -g
34 npm test
My Jest version in package-lock.json
"#jest/core": {
"version": "24.9.0",
My node.js version is
v12.19.0
create-react-app version is
npx create-react-app --version
3.4.1
antd version is
antd#4.6.6
file: App.test.tsx testing file
import React from 'react';
import { render } from '#testing-library/react';
import App from './App';
import renderer from 'react-test-renderer';
import MyButton from './components/button';
it('renders a snapshot', () => {
const tree = renderer.create(<App/>).toJSON();
expect(tree).toMatchSnapshot();
});
it('MyButton', () => {
const tree = renderer.create(<MyButton/>).toJSON();
expect(tree).toMatchSnapshot();
});
My antd source file
import React from 'react'
import { Button } from 'antd';
const MyButton = () => {
const [value, setValue] = React.useState('')
// The event type is a "ChangeEvent"
// We pass in "HTMLInputElement" to the input
function onChange(e: React.ChangeEvent<HTMLInputElement>) {
setValue(e.target.value)
}
return <Button></Button>
}
export default MyButton;
When I ran npm test, I got this
FAIL src/App.test.tsx
● Test suite failed to run
Cannot find module 'react' from 'index.js'
However, Jest was able to find:
'components/button.tsx'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].
See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
at Object.<anonymous> (../../../node_modules/antd/lib/affix/index.js:26:37)

Dynamically import webpack in Node.js

I´m trying to dynamically import webpack in Node.js
if (condition) {
import('webpack').then(webpack => webpack);
}
However in my terminal I see the following error:
C:\Users\myUser\react\node_modules\#babel\core\lib\transformation\normalize-file.js:209
throw err;
^
SyntaxError: C:\Users\myUser\react\server\index.js: Support for the experimental syntax 'dynamicImport' isn't currently enabled (23:3):
19 |
20 | if (condition) {
> 21 | import('webpack').then(webpack => webpack);
| ^
22 |
Add #babel/plugin-syntax-dynamic-import (https://git.io/vb4Sv) to the 'plugins' section of your Babel config to enable parsing.
I have #babel/plugin-syntax-dynamic-import installed and in my .babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-proposal-class-properties"
]
}
I even tried to add it to the webpack conf file under the rule for .js with loader "babel-loader".
I´m trying to avoid CmJS
const webpack = require('webpack');
In any case I receive the same error and I cannot find a solution. Did anyone go through this? Thanks
add plugins: ["dynamic-import-webpack"] to .babelrc
and also install plug $npm i babel-plugin-dynamic-import-webpack --D

Use babel in Node console

I'm running node 4.6.1 and I'd like to get es6/7/8 syntax in the node console as I can get with Babel. I'm able to compile scripts fine with babel, for instance by running
babel-node ./index.js --presets es2015,stage-0
but I could not find how to get such syntax support in the console. For instance the node console doesn't understand things like
const filter = {...{ foo: 1 }, ...{ bar: 4 } }
or all the async/await things.
When running scripts with npm, npm loads scripts under node_modules/.bin that are not part of the PATH. So running
$ babel-node --presets es2015,stage-0
will fail with
-bash: babel-node: command not found
but
$ node_modules/.bin/babel-node --presets es2015,stage-0
will work just fine. I'll get a node console where I can do:
> const filter = {...{ foo: 1 }, ...{ bar: 4 } }
> filter
{ foo: 1, bar: 4 }
> const a = async () => {}

What's wrong with my babel?

I have installed babel with npm install -g babel-cli and tested it with babel-node --version. The output is 6.2.0.
Then I tested it like below.
C:\Users\xuhang\Documents\work\CDT\cdt3.0\babel>babel-node
> console.log([1,2,3].map(x => x * x))
repl:1
console.log([1, 2, 3].map(x => x * x));
^^
SyntaxError: Unexpected token =>
at Object.exports.runInThisContext (vm.js:73:16)
at _eval (C:\Users\xuhang\AppData\Roaming\npm\node_modules\babel-cli\lib\_b
abel-node.js:102:26)
at REPLServer.replEval (C:\Users\xuhang\AppData\Roaming\npm\node_modules\ba
bel-cli\lib\_babel-node.js:187:14)
at bound (domain.js:254:14)
at REPLServer.runBound [as eval] (domain.js:267:12)
at REPLServer.<anonymous> (repl.js:279:12)
at REPLServer.emit (events.js:107:17)
at REPLServer.Interface._onLine (readline.js:214:10)
at REPLServer.Interface._line (readline.js:553:8)
at REPLServer.Interface._ttyWrite (readline.js:830:14)
>
Could you tell me what's wrong with console.log([1,2,3].map(x => x * x))?
Another simliar issue is below. It's so hard for me to learn babel, the initial test all failed.
What's inside the directory source is the example.js within the official sample provided by React below.
https://facebook.github.io/react/docs/tutorial.html
C:\Users\xuhang\Documents\work\CDT\cdt3.0\babel>babel source/ --watch --out-dir
build/
SyntaxError: source/example.js: Unexpected token (17:6)
15 | var rawMarkup = marked(this.props.children.toString(), {sanitize: tru
e});
16 | return (
> 17 | <div className="comment">
| ^
18 | <h2 className="commentAuthor">
19 | {this.props.author}
20 | </h2>
You've forgotten to create a .babelrc file. Pre 6.x version of Babel contained a few presets for Babel to transpile code out of the box, in 6.x it does not so you need to install the presets you want and in your case you need two: babel-preset-es2015 and babel-preset-react.
After you've installed them both npm install babel-preset-es2015 babel-preset-react add them to your .babelrc file
{
"presets": ["es2015", "react"]
}

babel-node not recognizing jsx <

I am trying to run some code that uses React and JSX using babel-node, which is part of the babel-cli. To the best of my knowledge the code is correct and I am using babel-node as expected, but hopefully someone can provide more insight.
The following error is generated.
(!535)-> babel-node server.js
/Users/eprouty/.nvm/versions/v5.0.0/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/index.js:520
throw err;
^
SyntaxError: /Users/ep/git/dgcastle/server.js: Unexpected token (60:51)
58 | res.status(302).redirect(redirectLocation.pathname + redirectLocation.search)
59 | } else if (renderProps) {
> 60 | var html = ReactDOM.renderToString(<RoutingContext {...renderProps} />);
| ^
61 | var page = jade.renderFile('views/index.jade', {html: html});
62 | res.status(200).send(page);
63 | } else {
at Parser.pp.raise (/Users/ep/.nvm/versions/v5.0.0/lib/node_modules/babel-cli/node_modules/babylon/lib/parser/location.js:24:13)
at Parser.pp.unexpected (/Users/ep/.nvm/versions/v5.0.0/lib/node_modules/babel-cli/node_modules/babylon/lib/parser/util.js:91:8)
at Parser.pp.parseExprAtom (/Users/ep/.nvm/versions/v5.0.0/lib/node_modules/babel-cli/node_modules/babylon/lib/parser/expression.js:507:12)
at Parser.pp.parseExprSubscripts (/Users/ep/.nvm/versions/v5.0.0/lib/node_modules/babel-cli/node_modules/babylon/lib/parser/expression.js:260:19)
at Parser.pp.parseMaybeUnary (/Users/ep/.nvm/versions/v5.0.0/lib/node_modules/babel-cli/node_modules/babylon/lib/parser/expression.js:240:19)
at Parser.pp.parseExprOps (/Users/ep/.nvm/versions/v5.0.0/lib/node_modules/babel-cli/node_modules/babylon/lib/parser/expression.js:171:19)
at Parser.pp.parseMaybeConditional (/Users/ep/.nvm/versions/v5.0.0/lib/node_modules/babel-cli/node_modules/babylon/lib/parser/expression.js:153:19)
at Parser.pp.parseMaybeAssign (/Users/ep/.nvm/versions/v5.0.0/lib/node_modules/babel-cli/node_modules/babylon/lib/parser/expression.js:120:19)
at Parser.pp.parseExprListItem (/Users/ep/.nvm/versions/v5.0.0/lib/node_modules/babel-cli/node_modules/babylon/lib/parser/expression.js:966:16)
at Parser.pp.parseCallExpressionArguments (/Users/ep/.nvm/versions/v5.0.0/lib/node_modules/babel-cli/node_modules/babylon/lib/parser/expression.js:336:20)
I can provide additional code snippets if that would help but the offending block is already included in the error message. Thanks for any insight you can provide!
If you are running version 6.x of babel, you need to use the babel react preset (as stated here).
If you are using babel 6.x, you will need to install the relevant preset/plugins. To get started, you can run npm install -g babel babel-preset-react and then run babel --presets react --watch src/ --out-dir lib/. For more information: check out the babel 6 blog post

Resources