How to transpile a JSX file in command line - babeljs

I am pretty new to React, I tried to follow the topic about pretranspile JSX:
https://facebook.github.io/react/docs/tooling-integration.html
My code [app.js] is very simple:
var React = require("react");
var ReactDOM = require("react-dom");
var Todo = React.createClass({
render: function() {
return <button>Add</button>;
}
});
ReactDOM.render(<Todo />, docuemtn.getElementById("div1"))
I first install:
npm install -g babel-cli
npm install react react-dom
Then try to use:
babel --watch ./app.js --out-dir ./
But it always says:
SyntaxError: ./app.jsx: Unexpected token (10:9)
8 | var Todo = React.createClass({
9 | render: function() {
> 10 | return <div>Hello {this.props.name}</div>;
| ^
11 | }
12 | });
13 |
I wonder how to solve this?

Babel 6 and up no longer has any native transforms for React. You have to add a preset like this
npm install babel-preset-react
And then run
babel --presets react --watch ./main.js --out-dir ./
Don't forget the --presets react part. After that it should work just fine.

install babel together with plugin to tranform react-jsx
npm install --save-dev babel-cli babel-preset-env babel-plugin-transform-react-jsx
run below command to compile jsx file
./node_modules/babel-cli/bin/babel.js --plugins transform-react-jsx test.jsx

Related

Getting this error with the #metaplex-foundation/js-next SDK

Currently working on a react app and I'm getting this error after installing metaplex.
My react-scripts version is 4.0.3
./node_modules/#metaplex-foundation/js-next/dist/esm/programs/token/gpaBuilders/TokenGpaBuilder.mjs
Can't import the named export 'ACCOUNT_SIZE' from non EcmaScript module (only default export is available)
I found out the solution in the git of metaplex here. I will leave you here the whole answer anyway.
Getting Started with Metaplex and CRA 5
This example sets up a new React app with Metaplex using "Create React App" (CRA) version 5 — i.e. using Webpack 5.
This example has been generated using the following steps:
Create a new project using the "Create React App" command.
npx create-react-app getting-started-react-cra5
cd getting-started-react-cra5
Install the Metaplex and the Solana SDKs.
npm install #metaplex-foundation/js #solana/web3.js
Install some polyfills.
npm install assert util crypto-browserify stream-browserify
Install and use react-app-rewired.
# Installs react-app-rewired.
npm install react-app-rewired
# Replaces "react-scripts" with "react-app-rewired" in package.json scripts.
sed -i '' 's/react-scripts /react-app-rewired /g' package.json
Override Webpack 5 configurations.
Create a new file to override Webpack 5 configurations.
touch config-overrides.js
Copy the following code inside the new config-overrides.js file.
const webpack = require("webpack");
module.exports = function override(webpackConfig) {
// Disable resolving ESM paths as fully specified.
// See: https://github.com/webpack/webpack/issues/11467#issuecomment-691873586
webpackConfig.module.rules.push({
test: /\.m?js/,
resolve: {
fullySpecified: false,
},
});
// Ignore source map warnings from node_modules.
// See: https://github.com/facebook/create-react-app/pull/11752
webpackConfig.ignoreWarnings = [/Failed to parse source map/];
// Polyfill Buffer.
webpackConfig.plugins.push(
new webpack.ProvidePlugin({ Buffer: ["buffer", "Buffer"] })
);
// Polyfill other modules.
webpackConfig.resolve.fallback = {
crypto: require.resolve("crypto-browserify"),
stream: require.resolve("stream-browserify"),
util: require.resolve("util"),
assert: require.resolve("assert"),
fs: false,
process: false,
path: false,
zlib: false,
};
return webpackConfig;
};
Update your browser requirements.
Update the browserslist object of your package.json to include the following production requirements.
"browserslist": {
"production": [
- ">0.2%",
- "not dead",
- "not op_mini all"
+ "chrome >= 67",
+ "edge >= 79",
+ "firefox >= 68",
+ "opera >= 54",
+ "safari >= 14"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
That's it!
You should not use #metaplex-foundation/js-next SDK, the actual repo is #metaplex-foundation/js, the name was changed and the updated repo is this, so try using #metaplex-foundation/js instead

Babel Not working for imports from node_modules

I just discovered RollUP and I am stuck with an issue where Babel does not run for imports from node_modules.
Here is an example:
My Javascript Code
import { _map } from "#varunsridharan/js-vars"
const myarray = _map.call([1,2,3,4],(x)=> x * 2);
console.log(myarray);
Rollup Config
import { babel } from '#rollup/plugin-babel';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import { uglify } from 'rollup-plugin-uglify';
import filesize from 'rollup-plugin-filesize';
import visualizer from 'rollup-plugin-visualizer';
export default {
input: './src/index.js',
output: {
file: './dist/myfile.min.js',
format: 'iife',
plugins: [
uglify( { mangle: true } ),
]
},
plugins: [
nodeResolve(),
babel(),
filesize(),
visualizer()
]
};
When I run rollup -c in CLI I get this output:
babelHelpers: 'bundled' option was used by default. It is recommended to configure this option explicitly, read more here: https://github.com/rollup/plugins/tree/master/packages/babel#babelhelpers
198 | * Array Related Vars.
199 | */
> 200 | const Arr = Array;
| ^ Unexpected token: keyword «const»
201 | const _Arrayprop = Arr.prototype;
202 | const _filter = _Arrayprop.filter;
203 | const _push = _Arrayprop.push;
[!] (plugin uglify) Error: Unexpected token: keyword «const»
SyntaxError: Unexpected token: keyword «const»
at JS_Parse_Error.get (eval at <anonymous> (E:\localhost\www\javascript\dizzle\node_modules\uglify-js\tools\node.js:18:1), <anonymous>:69:23)
at reportError (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:107:11)
at reportClientError (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:87:10)
at execFunction (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:157:5)
at execHelper (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:139:5)
at execMethod (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:143:5)
at process.<anonymous> (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:64:7)
at process.emit (events.js:315:20)
at emit (internal/child_process.js:876:12)
at processTicksAndRejections (internal/process/task_queues.js:85:21)
Based on the output i was able to understand that babel did not run for the imported modules. so i checking the options provided for rollup babel plugin # (https://github.com/rollup/plugins/tree/master/packages/babel) and found that it has include AND exclude options and i tried with the below config
babel( {
include: [ "node_modules/#varunsridharan/*/**", "./src/**" ],
exclude: "node_modules/**",
} ),
Still, nothing happened so I tried without ./src/** in babel include config and found that babel is not running in my main javascript file which imports the node_modules's file
Node Module Project Link: https://github.com/varunsridharan/js-vars

Jest: Cannot use import statement outside a module

I got an error when I run test using Jest, I tried to fix this error for 2 hours. But, I couldn't fix it. My module is using gapi-script package and error is occurred in this package. However, I don't know why this is occurred and how to fix it.
jest.config.js
module.exports = {
"collectCoverage": true,
"rootDir": "./",
"testRegex": "__tests__/.+\\.test\\.js",
"transform": {
'^.+\\.js?$': "babel-jest"
},
"moduleFileExtensions": ["js"],
"moduleDirectories": [
"node_modules",
"lib"
]
}
babel.config.js
module.exports = {
presets: [
'#babel/preset-env',
]
};
methods.test.js
import methods, { typeToActions } from '../lib/methods';
methods.js
import { gapi } from "gapi-script";
...
Error Message
C:\haram\github\react-youtube-data-api\node_modules\gapi-script\index.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import
{ gapi, gapiComplete } from './gapiScript';
SyntaxError: Cannot use import statement outside a module
What is wrong with my setting?
As of this writing, Jest is in the process of providing support for ES6 modules. You can track the progress here:
https://jestjs.io/docs/en/ecmascript-modules
For now, you can eliminate this error by running this command:
node --experimental-vm-modules node_modules/.bin/jest
instead of simply:
jest
Be sure to check the link before using this solution.
I solved this with the help of Paulo Coghi's answer to another question -
Does Jest support ES6 import/export?
Step 1:
Add your test environment to .babelrc in the root of your project:
{
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Step 2:
Install the ECMAScript 6 transform plugin:
npm install --save-dev #babel/plugin-transform-modules-commonjs
Jest needs babel to work with modules.
For the testing alone, you do not need jest.config.js, just name the testfiles xxx.spec.js or xxx.test.js or put the files in a folder named test.
I use this babel.config.js:
module.exports = function (api) {
api.cache(true)
const presets = [
"#babel/preset-env"
]
return {
presets
}
}
Adding "type": "module" in package.json or using mjs as stated in other answers is not necessary when your setup is not too complicated.
I have also faced the same issue and this was resolved by adding following command-line option as a environment variable.
export NODE_OPTIONS=--experimental-vm-modules npx jest //linux
setx NODE_OPTIONS "--experimental-vm-modules npx jest" //windows
Upgrading Jest (package.json) to version 29 (latest as of now) solved this problem for me.

Babel 7 and babel-polyfill

After updating to babel 7 beta, looks like babel polyfill does not transpile before bundle. I updated all scoped packages like this one "#babel/polyfill": "7.0.0-beta.36". And changed imports for two files from import 'babel-polyfill' to import '#babel/polyfill'. How to use babel/pollyfill with babel env and babel 7. Should I use babel/polyfill when use useBuiltIns: 'usage', with targets?
.babelrc.js
const nodeEnv = process.env.NODE_ENV || 'development'
let presetEnvConfig, plugins
if (nodeEnv === 'test'){
presetEnvConfig = {targets: {node: 'current'}}
plugins = ['istanbul']
} else {
presetEnvConfig = {
targets: {
browsers: ['last 2 versions', 'ie >= 11']
},
modules: false
}
plugins = ['react-hot-loader/babel']
}
const config = {
presets: [
['#babel/preset-env', presetEnvConfig],
'#babel/react',
'#babel/stage-2'
],
plugins,
}
types.js
import keyMirror from '../../../utils/keyMirror'
export default keyMirror({
Unassign: null,
Reassign: null,
QuickAssignment: null,
}, 'TagAssignmentTypes')
index.js
<Assignment
assignee={assignee}
tagId={tagId && tagId.toString(16)}
assignmentType={assignmentTypes.Reassign}
onRequestClose={() => this.setState({isAssignmentInProgress: false})}
onChange={onChange}
/>
#babel/polyfill is a wrapper package which only includes imports of stable core-js features (in Babel 6 it also included proposals) and regenerator-runtime/runtime, needed by transpiled generators and async functions. This package doesn't make it possible to provide a smooth migration path from core-js#2 to core-js#3: for this reason, it was decided to deprecate #babel/polyfill in favor of separate inclusion of required parts of core-js and regenerator-runtime.
Instead of
import "#babel/polyfill";
you should use those 2 lines:
import "core-js/stable";
import "regenerator-runtime/runtime";
Don't forget install those dependencies directly!
npm i --save core-js regenerator-runtime
Change
#babel/stage-2 to #babel/preset-stage-2
The following worked for me, add
**.babelrc**
{
"presets": [
["#babel/env"]
]
}
**app.js**
import "core-js/stable";
import "regenerator-runtime/runtime";
*Install as pointed by gianmarco*
npm i --save core-js regenerator-runtime

Unable to import snap.svg to ionic2 project

I followed documentation but I am not able to get snap.svg working in my Ionic2 project.
Install:
npm install snapsvg --save
npm install #types/snapsvg --save
Use:
import * as snapsvg from 'snapsvg';
var s = snapsvg.Snap(800,600);
Error:
Uncaught TypeError: Cannot read property 'on' of undefined
Any advices?
1) Install imports-loader and snap:
npm i imports-loader
npm i snapsvg
npm i #types/snapsvg
2) Create element in html template:
<svg width="200" height="200" id="svg"></svg>
3) Import it in your component:
import Snap from 'imports-loader?this=>window,fix=>module.exports=0!snapsvg/dist/snap.svg.js';
4) Use it in your component:
ionViewDidEnter() {
let s = Snap("#svg");
let circle = s.circle(50, 50, 100);
...
}