Babel 7 - Uncaught ReferenceError: regeneratorRuntime is not defined - reactjs

I'm getting the error Uncaught ReferenceError: regeneratorRuntime is not defined using React with webpack and Babel .
I've followed this answer by defining my .babel.rc as:
{
"presets": ["#babel/preset-env", "#babel/preset-react"] ,
"plugins": [
["#babel/plugin-transform-runtime"]
]
}
and running:
npm i --save-dev #babel/plugin-transform-runtime
However, I get the exact same error afterwards. I've also followed this other answer and this one, but still get the exact same error.
My babel specific installations in package.json are as follows:
"dependencies": {
"#babel/runtime": "^7.14.6"
},
"devDependencies": {
"#babel/core": "^7.14.6",
"#babel/plugin-transform-runtime": "^7.14.5",
"#babel/preset-env": "^7.14.7",
"#babel/preset-react": "^7.14.5"
}
Any ideas?

hey I ran into the same problem and I am using Babel 7, for me I installed these two dependencies:
npm install --save #babel/runtime
npm install --save-dev #babel/plugin-transform-runtime
And, in .babelrc, add:
{
"presets": ["#babel/preset-env"],
"plugins": [
["#babel/transform-runtime"]
]
}
and this solved my problem

{ "presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "9.2.1"
}
}
],
"#babel/preset-react" ] }
This is my file .babelrc
Look:
#babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!
your problemes:
You are using "# babel / preset-env" you must specify the version of node to compile. "node> 7.6". I recommend 10.
Why node > 7.6 Node.js 7.6 has shipped with official support for async/await enabled by default and better performance on low-memory devices.
How do you specify the version: It's simple
targets.node
string | "current".
If you want to compile against the current node version, you can specify "node": "current", which would be the same as "node": process.versions.node.
AND FOR ME LOOK LIKE THIS:
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "9.2.1"
}
}
],
"#babel/preset-react"
]
}
This allows the compiler to understand ASYNC AWAIT, hope it helps you!
You can also add a plugin to handle your "asyc away"
https://babeljs.io/docs/en/babel-plugin-transform-async-to-generator
ATTENTION - > This Config is for node-js; it is just a example

This ended up working for me:
How to allow async functions in React + Babel?
My problem was that I was defining the babel plugin in both my .babel.rc file and my webpack.config.js file. I needed to remove that plugin from my webpack.config.js and simply use it only in my .babel.rc file. Then it worked well.

Related

Uncaught Error: Cannot find module 'react-dom/client'

I just create my application from npm command, when i run the start script the application throws me that error.
Please provide more context. If you're using typescript on your react project. You need to upgrade both react and react-dom declaration. npm install #types/react#latest and npm install #types/react-dom#latest
If you've recently updated past npm 8.5+ and using workspaces, you have two options.
Option A) If possible, just remove your package.json declaring your "workspaces" (and the package-lock.json). I had only 1 workspace so that was the easiest fix.
Option B) Update Jest so it can find your modules. I've observed NPM 8.11 will create a node_modules in the workspaces folder and in each project.
Specifically look at the moduleDirectories key below.
{
verbose: true,
testEnvironment: "jsdom",
moduleFileExtensions: ["js", "jsx", "ts", "tsx"],
moduleDirectories: [
// Look in current directory node_modules
path.resolve(__dirname, "node_modules"),
// Look in parent workspace node_modules
path.resolve(__dirname, "../node_modules"),
],
moduleNameMapper: {
...moduleNameMapper,
"\\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
'\\.svg$': '<rootDir>/__mocks__/svgrMock.tsx',
"\\.(css)$": "identity-obj-proxy"
},
transform: {
"^.+\\.tsx?$": "ts-jest"
},
};

How to resolve "Cannot use import statement outside a module" in jest

I have a React application (not using Create React App) built using TypeScript, Jest, Webpack, and Babel. When trying to run yarn jest, I get the following error:
I have tried removing all packages and re-adding them. It does not resolve this. I have looked at similar questions and documentation and I am still misunderstanding something. I went so far as to follow another guide for setting up this environment from scratch and still received this issue with my code.
Dependencies include...
"dependencies": {
"#babel/plugin-transform-runtime": "^7.6.2",
"#babel/polyfill": "^7.6.0",
"babel-jest": "^24.9.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-test-renderer": "^16.11.0",
"source-map-loader": "^0.2.4"
},
"devDependencies": {
"#babel/core": "^7.6.0",
"#babel/preset-env": "^7.6.0",
"#babel/preset-react": "^7.0.0",
"#types/enzyme": "^3.9.2",
"#types/enzyme-adapter-react-16": "^1.0.5",
"#types/jest": "^24.0.13",
The component's import lines...
import * as React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./components/pages";
import {
Footer,
Header,
Navigation,
} from "./components/shared";
The test file....
import * as React from "react";
import * as renderer from "react-test-renderer";
import App from "../App";
it("Renders the Footer correctly", () => {
const tree = renderer
.create(<App />)
.toJSON();
expect(tree).toMatchSnapshot();
});
I expected to be able to use named imports in my components without my tests blowing up. It appears to fix the issue if I only use default imports through my solution, but I would prefer to not go that route.
Also using Babel, Typescript and Jest. Had the same failure, driving me crazy for hours.
Ended up creating a new babel.config.js file specifically for the tests. Had a large .babelrc that wasn't getting picked up by jest no matter what i did to it. Main app still uses the .babelrc as this overrides babel.config.js files.
Install jest, ts-jest and babel-jest:
npm i jest ts-jest babel-jest
babel.config.js (only used by jest)
module.exports = {presets: ['#babel/preset-env']}
jest.config.js
module.exports = {
preset: 'ts-jest',
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
"^.+\\.(js|jsx)$": "babel-jest",
}
};
package.json
"scripts": {
"test": "jest"
Use Babel to transpile those JS Modules and you'll be able to write your tests with es6.
Install Babel/preset-env
npm i -D #babel/preset-env
Create a babel configuration file with the preset
//babel.config.js
module.exports = {presets: ['#babel/preset-env']}
I solved this by migrating the .babelrc file to babel.config.js! Shocker.
For future references,
I solved the problem by using below jest config, after reading Logan Shoemaker's answer.
module.exports = {
verbose: true,
setupFilesAfterEnv: ["<rootDir>src/setupTests.ts"],
moduleFileExtensions: ["js", "jsx", "ts", "tsx"],
moduleDirectories: ["node_modules", "src"],
moduleNameMapper: {
"\\.(css|less|scss)$": "identity-obj-proxy"
},
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
"^.+\\.(js|jsx)$": "babel-jest",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/file.js",
}
};
try this thing if you are using babel 6
Adding #babel/plugin-transform-modules-commonjs in the plugin section of babel.config.js
or
For my case import issue was due to the react file drop by adding that to transformIgnorePatterns
"transformIgnorePatterns": ["/node_modules/(?!react-file-drop)"]
I fixed it by simply appending the pattern after the run statement in package.json runner
{
"scripts": {
...
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!my-library-dir)/'"
...
Then, just run npm test
Solution: my named imports were coming from index.js files and I believe ts-jest needed them as index.ts files (I'm using Typescript). If anyone else runs into this error, couldn't hurt to check if you derped your file extensions.
I wasted a lot of time on this, unfortunately, but I learned a lot about webpack configurations and Babel.
Add your test script in package.json with Node experimental feature: --experimental-vm-modules
In this way you won't require babel or other dependencies.
Examples:
"test": "NODE_OPTIONS='--experimental-vm-modules --experimental-specifier-resolution=node' jest"
If you get this error: zsh: command not found: jest, try with node passing jest.js like this:
"test": "NODE_OPTIONS='--experimental-vm-modules --experimental-specifier-resolution=node --trace-warnings' node node_modules/jest/bin/jest.js --detectOpenHandles"
I'm surprised that none of the answers does not give an elegant solution:
jest.config.js
module.exports = {
...,
globals: {
"ts-jest": {
isolatedModules: true,
},
},
};
This compiles each file separately therefore avoiding the no exports issue.
Create .babelrc on the main directory and add this code and install these packages
#babel/core, #babel/preset-env and #babel/preset-react
{
"presets": [
[
"#babel/preset-env",
{
"modules": "commonjs"
}
],
"#babel/preset-react"
]
}
Matching file extensions:
I importing a file named Todo.jsx in the root as ./src/Todo/. Whenever I changed it to Todo.js the problem went away.
Disclaimer: I'm not sure what the requirement is for having your file extension as jsx vs js for your components. It did not effect me at all, but I could imagine it could mess with intellisense or snippets.
For me renaming file to babel.config.js worked.
Here is my config file an NX project using next with Typescript along with Twin-macro
// .babelrc.js >> babel.config.js
module.exports = {
presets: [
[
"#nrwl/react/babel",
{
"runtime": "automatic",
"targets": {
"browsers": [">0.25%", "not dead"]
},
"preset-react": {
runtime: "automatic",
importSource: "#emotion/react",
},
}
],
'#babel/preset-env',
'#emotion/babel-preset-css-prop',
'#babel/preset-typescript'
],
plugins: ['#emotion', 'macros', '#babel/plugin-transform-runtime', 'react-docgen'],
}
Also, please note even updating package.json works,
https://kulshekhar.github.io/ts-jest/docs/getting-started/presets/#basic-usage
// package.json
"jest": {
// Replace `ts-jest` with the preset you want to use
// from the above list
"preset": "ts-jest"
}
I encountered the same problem with Typescript, Jest, and VueJS/VueCli 3. The normal build has no problem. only happens for Jest. I struggled for hours by searching. But no answer actually works. In my case, I have a dependency on my own typescript package which I specific "target": "es6" in the tsconfig.json. That's the root cause. So the solution is simply to change the dependent's (Not the same project) back to es5 tsconfig.json:
{
"compilerOptions": {
"target": "es5",
...
},
...
}
Personnaly I followed #ajwl setup but discovered that jsdom-worker inside setupFiles: section of jest.config.js was triggering that same error. Once removed, my tests were passing.
P.S. my babel.config.js is a bit different, since I have a Vuejs (v2) SPA (bundled with Vitejs):
module.exports = {
plugins: ['#babel/plugin-transform-modules-commonjs'],
presets: [['#babel/preset-env', { targets: { node: 'current' } }]]
}
The problem is likely that jest doesn't support esmodules natively. Which can cause problems if youre typescript target is es6 or greater.
If you are testing the built typescript output, you could simply add a module=commonjs flag while transpiling. That way, your code can run with es6 or greater and still work with Jest.
"scripts": {
"test": tsc --module commonjs && jest {your-output-folder}/
}
What's great about this is that I didn't have to add any additional babel dependencies or special jest runners :)
I solved it by changing my tsconfig.json to a compatible native output
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
It is not ideal in every scenario but you might be okay with this.
All I had to do, was simply updating the package #babel/preset-env in the dev dependencies to the latest version
// package.json
"#babel/preset-env": "^7.18.6"
None of the answers helped me, what did help me was making sure my NODE_ENV was set to test, since babel config is per NODE_ENV using the wrong NODE_ENV by accident that is not configured in babel config will mean you wont be using babel and the typescript files will not be transformed.
It took me couple of hours to figure this one out so i hope it will save someone else the time it took me.
Don't know why and how but how I solved the problem was really interesting.
Just add __mocks__ folder in your src folder and create an empty file inside __mocks__ named axios.js
I discovered that this error might be triggered when you try to load a dependency that is made for the browser and, thus, cannot work with jest (node).
I had a lot of trouble solving this issue for #zip.js/zip.js lib. But I could do it like that:
Here is my jest.config.js. Adapt it to your need. The trick here is the moduleNameMapper that will make all imports to zip.js point to the file __mocks__/#zip.js/zip.js I created in my root folder.
export default {
preset: 'ts-jest',
testEnvironment: 'node',
moduleNameMapper: {
'#zip.js/zip.js': '<rootDir>/__mocks__/#zip.js/zip.js',
},
}
And here is what I have in <rootDir>/__mocks__/#zip.js/zip.js file:
module.exports = {}
Too late for this answer :)
After trying all the possible solutions, this worked for me:
The solution, that works for me:
create a file named jest/mocks/#react-native-firebase/crashlytics.js
export default () => ({ log: jest.fn(), recordError: jest.fn(), });
create a file named jest/jestSetupFile.js
import mockFirebaseCrashlytics from './mocks/#react-native-firebase/crashlytics';
jest.mock('#react-native-firebase/crashlytics', () => mockFirebaseCrashlytics);
in package.json add
"jest": { "setupFiles": ["./jest/jestSetupFile.js"] },
I needed to do a couple things to get this to work for me
Rename my .babelrc to babel.config.js and make a little change:
// .babelrc
{
"presets": [
[
"#babel/preset-env",
{
"corejs": "3.26",
"useBuiltIns": "usage"
}
],
"#babel/preset-react"
],
...
}
// babel.config.js - This still works fine with webpack
module.exports = {
"presets": [
[
"#babel/preset-env",
{
"corejs": "3.26",
"useBuiltIns": "usage"
}
],
"#babel/preset-react"
],
...
}
Add the following to my jest config file:
{
...
"transformIgnorePatterns": [
"node_modules/(?!(react-leaflet-custom-control)/)"
],
...
}
Where react-leaflet-custom-control was the package causing issues for me.
If you're using TypeScript, and you have a tsconfig.json file, try removing "module": "esnext" if you're using it
Running npm ci fixed this problem for me.

relay-compiler unable to extract and use graphql queries in Typescript

I tried using relay with the Typescript react starter, and am running into multiple issues.
Seems like babel-plugin-relay is not able to sense the graphql statements extracted by the relay-compiler. Here is my compiler script
"relay": "relay-compiler --src ./src --schema ./src/schema.graphql --extensions=tsx --watchman false".
.babelrc
{
"babel": {
"presets": [
"react-app"
],
"plugins": [
"relay"
]
}
This is my error which suggests an issue with babel transpilation
graphql: Unexpected invocation at runtime. Either the Babel transform was not set up, or it failed to identify this call site. Make sure it is being used verbatim as `graphql`.
Essentially the problem resolves around pulling out the GraphQL tags from typescript during transformations. I figured out the solution thanks to work in these PRs #1710 and #2293.
Here are the steps:
Modify the webpack config to include a babel loader (the typescript starter only has a ts-loader).
...
test: /\.(ts|tsx)$/,
include: paths.appSrc,
exclude: /node_modules/,
use: [
{ loader: 'babel-loader' },
{
loader: require.resolve('ts-loader'),
options: {
transpileOnly: true,
},
},
],
...
Change the target and module configuration in tsconfig to es2015
...
"target": "es2015",
"module": "es2015",
...
Add relay-compiler-language-typescript
yarn add relay-compiler-language-typescript -D
Also add babel-plugin-transform-es2015-modules-commonjs.
yarn add babel-plugin-transform-es2015-modules-commonjs -D
Since now we are targetting es2015, this plugin is needed to support ES module import and export statements.
And a script to compile graphql statements
"relay": "relay-compiler --src ./src --schema src/schema.graphql --language typescript --artifactDirectory ./src/__generated__ --watch"
Point the relay plugin to use the artifacts generated by the above command in .babelrc
"plugins": [
"transform-es2015-modules-commonjs",
["relay", { "artifactDirectory": "./src/__generated__" }],
],
My .babelrc looks like this
{
"plugins": [
[
// Please note that the "relay" plugin should run before other plugins or presets to ensure the graphql template literals are correctly transformed. See Babel's documentation on this topic.
"relay",
{
"artifactDirectory": "./src/__generated__"
}
],
[
"transform-es2015-modules-commonjs",
{
"allowTopLevelThis": true
}
]
]
}
Follow the configuration steps here https://github.com/relay-tools/relay-compiler-language-typescript#typescript
that will link you to babel docs https://babeljs.io/docs/en/babel-plugin-transform-es2015-modules-commonjs/
this seems to be working. my npm script is
"relay": "relay-compiler --src ./src --schema ./data/schema.graphql --language typescript --artifactDirectory ./src/__generated__"
and tsconfig.json contains this
"target": "es2015",
"module": "es2015",
Update
I had to install babel-plugin-relay as described here https://create-react-app.dev/docs/adding-relay/
and hack the typescript types for it https://github.com/DefinitelyTyped/DefinitelyTyped/issues/35707

React-Native 0.57: 'Can't find variable: require' with metro-react-native-babel-preset

I started a multiplatform project with code sharing between react-native and react-js.
So I have a webpack setup for browser/Electron, and a react-native 0.57 setup for Android/iOS.
The problem I'm having right now is the following:
Can't find variable: require
It might be a very bald question, but do I need anything else? I read, that React-native should support require by itself, but couldn't find anything related to this setup yet.
.babelrc
{"presets": ["module:metro-react-native-babel-preset"]}
I'm also using #babel/polyfill and #babel/runtime on browser side, but I wonder if they would interfere.
Got the solution, my .babelrc was okay, but the packager cached the very first wrong one so I had to start the packager as:
react-native start --reset-cache
After looking at below github issue it looks like the issue is caused by corejs option #babel/plugin-transform-runtime, So replace it by #babel/polyfil
https://github.com/facebook/react-native/issues/21048
.babelrc config for ref
{
"presets": [
"module:metro-react-native-babel-preset",
],
"plugins": [
"react-require",
[
"module-resolver",
{
"root": [
"./src",
"./assets"
],
"alias": {
"app": "./src",
"assets": "./assets"
}
}
],
[
"babel-plugin-require-context-polyfill",
{
"alias": {
"app": "./src"
}
}
],
"#babel/plugin-proposal-export-default-from",
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-transform-flow-strip-types",
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-proposal-class-properties",
{
"loose": false
}
],
[
"#babel/plugin-transform-runtime",
{
}
],
],
"sourceMaps": true
}
Install Babel polyfill 7 "#babel/polyfill": "^7.0.0"
And import that in App component
import '#babel/polyfill'
It seems that react-native start --reset-cache works.

Error when testing react components with jest and css-modules

I'm trying to test my components with jest, react, redux but I keep getting the following error:
● Test suite failed to run
stream-react-redux/src/containers/App/App.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.app {
SyntaxError: Unexpected token .
I have followed the instructions on how to add the identity-obj-proxy and configuring my .jestrc file, but I keep getting the same error. The problem came when I started using css-modules and importing them in my components
Here is my .jestrc:
{
"moduleFileExtensions": [ "js", "jsx"],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"^.+\\.(css)$": "identity-obj-proxy"
},
"transform": {
"^.+\\.(js|jsx)$": "babel-jest"
},
"verbose": true
}
I have also added the ["es2015", { "modules": false } ] inside my .babelrc file.
So after trying everything, I was still getting the same error.
What I just noticed is that when I specify my config inside a .jestrc file my tests brake because of the .css, but when I do it from the package.json everything works.
EDIT
#package.json
"jest": {
"moduleNameMapper": {
"\\.css$": "identity-obj-proxy"
},
"transform": {
"\\.js$": "babel-jest"
}
I took a look at the Jest docs and, just to be clear, did you install identity-obj-proxy?
npm install --save-dev identity-obj-proxy
Also, I see that the recommended file regex in the Jest docs is
"\\.(css|less)$": "identity-obj-proxy"
may try switching yours to match.
Finally, you could try a jest plugin like jest-css-modules
https://github.com/justinsisley/Jest-CSS-Modules

Resources