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
Related
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
I have a component library that will be shipping with a few small assets (images). Those assets are imported into various components in the library.
The build script uses babel (without webpack) to transpile the js(x) to a build directory, and is currently dumping the images into build/assets/images.
This works when testing the build, but when using the component in another project (using webpack) the component tries to refer the node_modules folder:
Example component:
import myImage from './assets/images/myImage.png';
const MyComponent = () => (
<img src={myImage} />
);
export MyComponent;
Usage:
import MyComponent from 'myLibrary/MyComponent';
export default () => (
<MyComponent />
);
The error message:
myImage.png:1 GET http://localhost:9001/node_modules/myLibrary/assets/images/myImage.png 404 (Not Found)
As I understand the 'best' way to include assets is to use the url-loader so they're converted to data uri's. However, trying to use the url-loader without Webpack isn't working:
babel.config.js
...
plugins: [
[
"url-loader",
{
"extensions": ["png", "jpg", "jpeg", "gif", "svg", "pdf"],
"limit": 0
}
]
]
...
Error: Cannot find module 'babel-plugin-url-loader'
I found this and it works for PNG and SVG files - worked perfectly for what I needed!
https://www.npmjs.com/package/babel-plugin-inline-import-data-uri
My root dir structure is like so:
src
utils
types
clients
package.json
etc.
my current babel config i run is like:
{
presets: ['#babel/preset-env', '#babel/preset-typescript', '#babel/preset-react', '#babel/preset-flow'],
plugins: ['#babel/plugin-syntax-dynamic-import', '#babel/transform-runtime'],
env: {
build: {
ignore: ['**/*.spec.tsx', '**/*.spec.ts', '**/*.stories.tsx']
}
},
ignore: ['node_modules']
}
How do I allow various /src files directly imports from root. eg.
import { handyFunction } from 'utils'
import { api } from 'clients'
as opposed to doing this relatively:
import { handyFunction } from '../../../utils'
import { api } from '../../../clients'
You can use babel plugin module resolver as mentioned here https://www.npmjs.com/package/babel-plugin-module-resolver.
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.
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