Parsing Error The Keyword import is Reserved (SublimeLinter-contrib-eslint) - javascript

I have a problem with eslint, it gives me [Parsing Error The keyword import is reserve] this is only occur in sublime, in atom editor work well. I have eslint
.eslintrc.js
module.exports = {
"extends": "airbnb",
"plugins": [
"react"
]
};
package.json
{
"name": "paint",
"version": "0.0.0",
"description": "paint on the browser",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"paint",
"javascript"
],
"author": "",
"license": "ISC",
"devDependencies": {
"browserify": "^11.2.0",
"eslint": "^2.2.0",
"eslint-config-airbnb": "^2.1.1",
"eslint-plugin-react": "^3.11.2",
"gulp-babel": "^5.2.1",
"gulp-clean": "^0.3.1",
"gulp-stylus": "^2.2.0",
"vinyl-source-stream": "^1.1.0"
}
}

Add this to the root of your .eslintrc.json (formerly .eslintrc)
"parser": "babel-eslint"
and make sure to run:
npm install babel-eslint --save-dev

The eslint option that solves the "The keyword import is reserved" error is parserOptions.sourceType. Setting it to "module" allows the import keyword to be used.
.eslintrc
{
"parserOptions": {
"sourceType": "module"
}
}
Docs: https://eslint.org/docs/user-guide/configuring#specifying-parser-options

This is old answer - 2020 year
Not sure if this is still relevant as of now.
===
Spent 30 mins - trying all solutions but dint work, so sharing this one.
The issue is seen with new react app, and in Visual Studio Code, even at this time - Apr 2020.
Create a file .eslintrc.js in the root folder (beside package.json, or beside /src/ directory)
Paste below contents in .eslintrc.js
Restart your editor, like VS Code.
Now I can see real errors, instead of those fake import/export errors.
.eslintrc.js file contents:
module.exports = {
env: {
commonjs: true,
node: true,
browser: true,
es6: true,
jest: true,
},
extends: ["eslint:recommended", "plugin:react/recommended"],
globals: {},
parser: "babel-eslint",
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 2018,
sourceType: "module",
},
plugins: ["react", "import", "react-hooks"],
ignorePatterns: ["node_modules/"],
rules: {},
settings: {
react: {
version: "latest", // "detect" automatically picks the version you have installed.
},
},
};
Hope that helps.

The problem was i had installed eslint globally and locally, causing inconsistencies in SublimeLinter-contrib-eslint. I uninstalled eslint globally and SublimeLinter is working.

Closing VS code and re-open it does the trick for me...

Not sure about it but try to rename your file to .eslintrc and just use
{
"extends": "airbnb",
"plugins": ["react"]
};
Also be sure you have the required packages installed.
github.com/airbnb/javascript

The accepted answer works, however, is no longer under maintenance and the newly suggested approach is to use the version from the mono repo instead.
Installation
$ npm install eslint #babel/core #babel/eslint-parser --save-dev
# or
$ yarn add eslint #babel/core #babel/eslint-parser -D
.eslintrc.js
module.exports = {
parser: "#babel/eslint-parser",
};
Reference

i also got this error in a meteor project and i could solved it setting sourceType to "module"
more details can be found in Eslint docs:
http://eslint.org/docs/user-guide/configuring#specifying-parser-options

This config worked for me. (I am using create-react-app but applicable to any eslint project)
.eslintrc (create file in root if it doesnt exist)
{
"rules": {
"jsx-a11y/anchor-is-valid": [ "error", {
"components": [ "Link" ],
"specialLink": [ "to" ]
}]
},
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2015
}
}

The same issue occurred when creating js files within a typescript react-native project while eslint is enabled.
Changing the file type from js to ts resolved the issue.
Also, adding the .eslintrc.js file as mentioned in previous answers resolved the issue without changing the file type from js to ts.
module.exports = {
parser: "#babel/eslint-parser",
};

The issue is seen with the new react app, and in Visual Studio Code, even at this time - August 2022
Create a file .eslintrc.js in the root folder
Paste the below contents in .eslintrc.js
Restart your editor, like VS Code.
Now I can see real errors, instead of those fake import/export errors.
.eslintrc.js file contents:
export const parser = "#babel/eslint-parser";
The accepted answer works, however, the newly suggested approach is to use the version from ES6.

Adding ecmaVersion to .eslintrc.json fixed the issue
{
"ecmaVersion": 2015,
"extends": [
"eslint:recommended",
"plugin:react/recommended"
]
}

I found this issue while creating the vue project (Used Editor: Visual Code)
Install babel-eslint package
npm install babel-eslint
Create the .eslintrc.js file and add below code
module.exports = {
root: true,
parserOptions: {
'sourceType': 'module',
parser: 'babel-eslint'
}
}
npm run serve, that error will be resolved like magic.

Related

Getting errors on trying to use javascript latest features [duplicate]

I'm trying to use async/await from scratch on Babel 6, but I'm getting regeneratorRuntime is not defined.
.babelrc file
{
"presets": [ "es2015", "stage-0" ]
}
package.json file
"devDependencies": {
"babel-core": "^6.0.20",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.js file
"use strict";
async function foo() {
await bar();
}
function bar() { }
exports.default = foo;
Using it normally without the async/await works just fine. Any ideas what I'm doing wrong?
babel-polyfill (deprecated as of Babel 7.4) is required. You must also install it in order to get async/await working.
npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader
package.json
"devDependencies": {
"babel-core": "^6.0.20",
"babel-polyfill": "^6.0.16",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.babelrc
{
"presets": [ "es2015", "stage-0" ]
}
.js with async/await (sample code)
"use strict";
export default async function foo() {
var s = await bar();
console.log(s);
}
function bar() {
return "bar";
}
In the startup file
require("babel-core/register");
require("babel-polyfill");
If you are using webpack you need to put it as the first value of your entry array in your webpack configuration file (usually webpack.config.js), as per #Cemen comment:
module.exports = {
entry: ['babel-polyfill', './test.js'],
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel', }
]
}
};
If you want to run tests with babel then use:
mocha --compilers js:babel-core/register --require babel-polyfill
Note
If you're using babel 7, the package has been renamed to #babel/plugin-transform-runtime.
Besides polyfill, I use babel-plugin-transform-runtime. The plugin is described as:
Externalize references to helpers and builtins, automatically polyfilling your code without polluting globals. What does this actually mean though? Basically, you can use built-ins such as Promise, Set, Symbol etc as well use all the Babel features that require a polyfill seamlessly, without global pollution, making it extremely suitable for libraries.
It also includes support for async/await along with other built-ins of ES 6.
$ npm install --save-dev babel-plugin-transform-runtime
In .babelrc, add the runtime plugin
{
"plugins": [
["transform-runtime", {
"regenerator": true
}]
]
}
Babel 7 Users
I had some trouble getting around this since most information was for prior babel versions. For Babel 7, install 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"]
]
}
Update
It works if you set the target to Chrome. But it might not work for other targets, please refer to: https://github.com/babel/babel-preset-env/issues/112
So this answer is NOT quite proper for the original question. I will keep it here as a reference to babel-preset-env.
A simple solution is to add import 'babel-polyfill' at the beginning of your code.
If you use webpack, a quick solution is to add babel-polyfill as shown below:
entry: {
index: ['babel-polyfill', './index.js']
}
I believe I've found the latest best practice.
Check this project: https://github.com/babel/babel-preset-env
yarn add --dev babel-preset-env
Use the following as your babel configuration:
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 Chrome versions"]
}
}]
]
}
Then your app should be good to go in the last 2 versions of Chrome browser.
You can also set Node as the targets or fine-tune the browsers list according to https://github.com/ai/browserslist
Tell me what, don't tell me how.
I really like babel-preset-env's philosophy: tell me which environment you want to support, do NOT tell me how to support them. It's the beauty of declarative programming.
I've tested async await and they DO work. I don't know how they work and I really don't want to know. I want to spend my time on my own code and my business logic instead. Thanks to babel-preset-env, it liberates me from the Babel configuration hell.
Update: The Babel 7 post also has a more in-depth answer.
Babel 7.4.0 or later (core-js 2 / 3)
As of Babel 7.4.0, #babel/polyfill is deprecated.
In general, there are two ways to install polyfills/regenerator: via global namespace (Option 1) or as ponyfill (Option 2, without global pollution).
Option 1: #babel/preset-env
presets: [
["#babel/preset-env", {
"useBuiltIns": "usage",
"corejs": 3, // or 2,
"targets": {
"firefox": "64", // or whatever target to choose .
},
}]
]
will automatically use regenerator-runtime and core-js according to your target. No need to import anything manually. Don't forget to install runtime dependencies:
npm i --save regenerator-runtime core-js
Alternatively, set useBuiltIns: "entry" and import it manually:
import "regenerator-runtime/runtime";
import "core-js/stable"; // if polyfills are also needed
Option 2: #babel/transform-runtime with #babel/runtime
This alternative has no global scope pollution and is suitable for libraries.
{
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"regenerator": true,
"corejs": 3 // or 2; if polyfills needed
...
}
]
]
}
Install it:
npm i -D #babel/plugin-transform-runtime
npm i #babel/runtime
If corejs polyfill is used, you replace #babel/runtime with #babel/runtime-corejs2 (for "corejs": 2) or #babel/runtime-corejs3 (for "corejs": 3).
Alternatively, if you don't need all the modules babel-polyfill provides, you can just specify babel-regenerator-runtime in your webpack config:
module.exports = {
entry: ['babel-regenerator-runtime', './test.js'],
// ...
};
When using webpack-dev-server with HMR, doing this reduced the number of files it has to compile on every build by quite a lot. This module is installed as part of babel-polyfill so if you already have that you're fine, otherwise you can install it separately with npm i -D babel-regenerator-runtime.
My simple solution:
npm install --save-dev babel-plugin-transform-runtime
npm install --save-dev babel-plugin-transform-async-to-generator
.babelrc
{
"presets": [
["latest", {
"es2015": {
"loose": true
}
}],
"react",
"stage-0"
],
"plugins": [
"transform-runtime",
"transform-async-to-generator"
]
}
This error is caused when async/await functions are used without the proper Babel plugins. As of March 2020, the following should be all you need to do. (#babel/polyfill and a lot of the accepted solutions have been deprecated in Babel. Read more in the Babel docs.)
In the command line, type:
npm install --save-dev #babel/plugin-transform-runtime
In your babel.config.js file, add this plugin #babel/plugin-transform-runtime. Note: The below example includes the other presets and plugins I have for a small React/Node/Express project I worked on recently:
module.exports = {
presets: ['#babel/preset-react', '#babel/preset-env'],
plugins: ['#babel/plugin-proposal-class-properties',
'#babel/plugin-transform-runtime'],
};
babel-regenerator-runtime is now deprecated, instead one should use regenerator-runtime.
To use the runtime generator with webpack and babel v7:
install regenerator-runtime:
npm i -D regenerator-runtime
And then add within webpack configuration :
entry: [
'regenerator-runtime/runtime',
YOUR_APP_ENTRY
]
Update your .babelrc file according to the following examples, it will work.
If you are using #babel/preset-env package
{
"presets": [
[
"#babel/preset-env", {
"targets": {
"node": "current"
}
}
]
]
}
or if you are using babel-preset-env package
{
"presets": [
[
"env", {
"targets": {
"node": "current"
}
}
]
]
}
As of Oct 2019 this worked for me:
Add this to the preset.
"presets": [
"#babel/preset-env"
]
Then install regenerator-runtime using npm.
npm i regenerator-runtime
And then in your main file use: (this import is used only once)
import "regenerator-runtime/runtime";
This is will enable you to use async awaits in your file and remove the regenerator error
Be careful of hoisted functions
I had both my 'polyfill import' and my 'async function' in the same file, however I was using the function syntax that hoists it above the polyfill which would give me the ReferenceError: regeneratorRuntime is not defined error.
Change this code
import "babel-polyfill"
async function myFunc(){ }
to this
import "babel-polyfill"
var myFunc = async function(){}
to prevent it being hoisted above the polyfill import.
If using babel-preset-stage-2 then just have to start the script with --require babel-polyfill.
In my case this error was thrown by Mocha tests.
Following fixed the issue
mocha \"server/tests/**/*.test.js\" --compilers js:babel-register --require babel-polyfill
I had this problem in Chrome. Similar to RienNeVaPlu͢s’s answer, this solved it for me:
npm install --save-dev regenerator-runtime
Then in my code:
import 'regenerator-runtime/runtime';
Happy to avoid the extra 200 kB from babel-polyfill.
I used tip from https://github.com/babel/babel/issues/9849#issuecomment-592668815 and added targets: { esmodules: true,} to my babel.config.js.
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
esmodules: true,
},
},
],
],
}
You're getting an error because async/await use generators, which are an ES2016 feature, not ES2015. One way to fix this is to install the babel preset for ES2016 (npm install --save babel-preset-es2016) and compile to ES2016 instead of ES2015:
"presets": [
"es2016",
// etc...
]
As the other answers mention, you can also use polyfills (though make sure you load the polyfill first before any other code runs). Alternatively, if you don't want to include all of the polyfill dependencies, you can use the babel-regenerator-runtime or the babel-plugin-transform-runtime.
I started getting this error after converting my project into a typescript project. From what I understand, the problem stems from async/await not being recognized.
For me the error was fixed by adding two things to my setup:
As mentioned above many times, I needed to add babel-polyfill into my webpack entry array:
...
entry: ['babel-polyfill', './index.js'],
...
I needed to update my .babelrc to allow the complilation of async/await into generators:
{
"presets": ["es2015"],
"plugins": ["transform-async-to-generator"]
}
DevDependencies:
I had to install a few things into my devDependencies in my package.json file as well. Namely, I was missing the babel-plugin-transform-async-to-generator, babel-polyfill and the babel-preset-es2015:
"devDependencies": {
"babel-loader": "^6.2.2",
"babel-plugin-transform-async-to-generator": "^6.5.0",
"babel-polyfill": "^6.5.0",
"babel-preset-es2015": "^6.5.0",
"webpack": "^1.12.13"
}
Full Code Gist:
I got the code from a really helpful and concise GitHub gist you can find here.
I fixed this error by installing babel-polyfill
npm install babel-polyfill --save
then I imported it in my app entry point
import http from 'http';
import config from 'dotenv';
import 'babel-polyfill';
import { register } from 'babel-core';
import app from '../app';
for testing I included --require babel-polyfill in my test script
"test": "export NODE_ENV=test|| SET NODE_ENV=test&& mocha --compilers
js:babel-core/register --require babel-polyfill server/test/**.js --exit"
There are so many answers up there, I will post my answer for my reference.
I use webpack and react, here is my solution without the .babelrc file
I am working on this in Aug 2020
Install react and babel
npm i #babel/core babel-loader #babel/preset-env #babel/preset-react react react-dom #babel/plugin-transform-runtime --save-dev
Then in my webpack.config.js
// other stuff
module.exports = {
// other stuff
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env',"#babel/preset-react"],
plugins: ['#babel/plugin-proposal-class-properties', '#babel/plugin-transform-runtime'],
//npm install --save-dev #babel/plugin-transform-runtime
}
}
},
],
},
};
I just don't know why I dont need to install the async package for the moment
New Answer Why you follow my answer ?
Ans: Because I am going to give you a answer with latest Update version npm project .
04/14/2017
"name": "es6",
"version": "1.0.0",
"babel-core": "^6.24.1",
"babel-loader": "^6.4.1",
"babel-polyfill": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"webpack": "^2.3.3",
"webpack-dev-server": "^2.4.2"
If your Use this version or more UP version of Npm and all other ...
SO just need to change :
webpack.config.js
module.exports = {
entry: ["babel-polyfill", "./app/js"]
};
After change webpack.config.js files Just add this line to top of your code .
import "babel-polyfill";
Now check everything is ok. Reference LINK
Also Thanks #BrunoLM for his nice Answer.
The targeted browsers I need to support already support async/await, but when writing mocha tests, without the proper setting I still got this error.
Most of the articles I googled are outdated, including the accepted answer and high voted answers here, i.e. you don't need polyfill, babel-regenerator-runtime, babel-plugin-transform-runtime. etc. if your target browser(s) already supports async/await (of course if not you need polyfill)
I don't want to use webpack either.
Tyler Long's answer is actually on the right track since he suggested babel-preset-env (but I omitted it first as he mentioned polifill at the beginning). I still got the ReferenceError: regeneratorRuntime is not defined at the first then I realized it was because I didn't set the target. After setting the target for node I fix the regeneratorRuntime error:
"scripts": {
//"test": "mocha --compilers js:babel-core/register"
//https://github.com/mochajs/mocha/wiki/compilers-deprecation
"test": "mocha --require babel-core/register"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-preset-env": "^1.7.0",
"mocha": "^5.2.0"
},
//better to set it .bablerc, I list it here for brevity and it works too.
"babel": {
"presets": [
["env",{
"targets": {
"node": "current"
"chrome": 66,
"firefox": 60,
},
"debug":true
}]
]
}
My working babel 7 boilerplate for react with regenerator runtime:
.babelrc
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": true,
},
},
],
"#babel/preset-react",
],
"plugins": [
"#babel/plugin-syntax-class-properties",
"#babel/plugin-proposal-class-properties"
]
}
package.json
...
"devDependencies": {
"#babel/core": "^7.0.0-0",
"#babel/plugin-proposal-class-properties": "^7.4.4",
"#babel/plugin-syntax-class-properties": "^7.2.0",
"#babel/polyfill": "^7.4.4",
"#babel/preset-env": "^7.4.5",
"#babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
...
main.js
import "#babel/polyfill";
....
Easiest way to fix this 'regeneratorRuntime not defined issue' in your console:
You don't have to install any unnecessary plugins. Just add:
<script src="https://unpkg.com/regenerator-runtime#0.13.1/runtime.js"></script>
inside of the body in your index.html.
Now regeneratorRuntime should be defined once you run babel and now your async/await functions should be compiled successfully into ES2015
Just install regenerator-runtime
with below command
npm i regenerator-runtime
add below line in startup file before you require server file
require("regenerator-runtime/runtime");
So far this has been working for me
I get this error using gulp with rollup when I tried to use ES6 generators:
gulp.task('scripts', () => {
return rollup({
entry: './app/scripts/main.js',
format: "iife",
sourceMap: true,
plugins: [babel({
exclude: 'node_modules/**',
"presets": [
[
"es2015-rollup"
]
],
"plugins": [
"external-helpers"
]
}),
includePaths({
include: {},
paths: ['./app/scripts'],
external: [],
extensions: ['.js']
})]
})
.pipe(source('app.js'))
.pipe(buffer())
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('.tmp/scripts'))
.pipe(reload({ stream: true }));
});
I may case the solution was to include babel-polyfill as bower component:
bower install babel-polyfill --save
and add it as dependency in index.html:
<script src="/bower_components/babel-polyfill/browser-polyfill.js"></script>
1 - Install babel-plugin-transform-async-to-module-method,
babel-polyfil, bluebird , babel-preset-es2015, babel-core :
npm install babel-plugin-transform-async-to-module-method babel-polyfill bluebird babel-preset-es2015 babel-core
2 - Add in your js babel polyfill:
import 'babel-polyfill';
3 - Add plugin in your .babelrc:
{
"presets": ["es2015"],
"plugins": [
["transform-async-to-module-method", {
"module": "bluebird",
"method": "coroutine"
}]
]
}
Source : http://babeljs.io/docs/plugins/transform-async-to-module-method/
For people looking to use the babel-polyfill version 7^ do this with webpack ver3^.
Npm install the module npm i -D #babel/polyfill
Then in your webpack file in your entry point do this
entry: ['#babel/polyfill', path.resolve(APP_DIR, 'App.js')],
To babel7 users and ParcelJS >= 1.10.0 users
npm i #babel/runtime-corejs2
npm i --save-dev #babel/plugin-transform-runtime #babel/core
.babelrc
{
"plugins": [
["#babel/plugin-transform-runtime", {
"corejs": 2
}]
]
}
taken from https://github.com/parcel-bundler/parcel/issues/1762
I had a setup
with webpack using presets: ['es2015', 'stage-0']
and mocha that was running tests compiled by webpack.
To make my async/await in tests work all I had to do is use mocha with the --require babel-polyfill option:
mocha --require babel-polyfill
I am using a React and Django project and got it to work by using regenerator-runtime. You should do this because #babel/polyfill will increase your app's size more and is also deprecated. I also followed this tutorial's episode 1 & 2 to create my project's structure.
*package.json*
...
"devDependencies": {
"regenerator-runtime": "^0.13.3",
...
}
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["transform-class-properties"]
}
index.js
...
import regeneratorRuntime from "regenerator-runtime";
import "regenerator-runtime/runtime";
ReactDOM.render(<App />, document.getElementById('app'));
...

regeneratorRuntime not defined in Node when building with babel [duplicate]

I'm trying to use async/await from scratch on Babel 6, but I'm getting regeneratorRuntime is not defined.
.babelrc file
{
"presets": [ "es2015", "stage-0" ]
}
package.json file
"devDependencies": {
"babel-core": "^6.0.20",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.js file
"use strict";
async function foo() {
await bar();
}
function bar() { }
exports.default = foo;
Using it normally without the async/await works just fine. Any ideas what I'm doing wrong?
babel-polyfill (deprecated as of Babel 7.4) is required. You must also install it in order to get async/await working.
npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader
package.json
"devDependencies": {
"babel-core": "^6.0.20",
"babel-polyfill": "^6.0.16",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.babelrc
{
"presets": [ "es2015", "stage-0" ]
}
.js with async/await (sample code)
"use strict";
export default async function foo() {
var s = await bar();
console.log(s);
}
function bar() {
return "bar";
}
In the startup file
require("babel-core/register");
require("babel-polyfill");
If you are using webpack you need to put it as the first value of your entry array in your webpack configuration file (usually webpack.config.js), as per #Cemen comment:
module.exports = {
entry: ['babel-polyfill', './test.js'],
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel', }
]
}
};
If you want to run tests with babel then use:
mocha --compilers js:babel-core/register --require babel-polyfill
Note
If you're using babel 7, the package has been renamed to #babel/plugin-transform-runtime.
Besides polyfill, I use babel-plugin-transform-runtime. The plugin is described as:
Externalize references to helpers and builtins, automatically polyfilling your code without polluting globals. What does this actually mean though? Basically, you can use built-ins such as Promise, Set, Symbol etc as well use all the Babel features that require a polyfill seamlessly, without global pollution, making it extremely suitable for libraries.
It also includes support for async/await along with other built-ins of ES 6.
$ npm install --save-dev babel-plugin-transform-runtime
In .babelrc, add the runtime plugin
{
"plugins": [
["transform-runtime", {
"regenerator": true
}]
]
}
Babel 7 Users
I had some trouble getting around this since most information was for prior babel versions. For Babel 7, install 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"]
]
}
Update
It works if you set the target to Chrome. But it might not work for other targets, please refer to: https://github.com/babel/babel-preset-env/issues/112
So this answer is NOT quite proper for the original question. I will keep it here as a reference to babel-preset-env.
A simple solution is to add import 'babel-polyfill' at the beginning of your code.
If you use webpack, a quick solution is to add babel-polyfill as shown below:
entry: {
index: ['babel-polyfill', './index.js']
}
I believe I've found the latest best practice.
Check this project: https://github.com/babel/babel-preset-env
yarn add --dev babel-preset-env
Use the following as your babel configuration:
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 Chrome versions"]
}
}]
]
}
Then your app should be good to go in the last 2 versions of Chrome browser.
You can also set Node as the targets or fine-tune the browsers list according to https://github.com/ai/browserslist
Tell me what, don't tell me how.
I really like babel-preset-env's philosophy: tell me which environment you want to support, do NOT tell me how to support them. It's the beauty of declarative programming.
I've tested async await and they DO work. I don't know how they work and I really don't want to know. I want to spend my time on my own code and my business logic instead. Thanks to babel-preset-env, it liberates me from the Babel configuration hell.
Update: The Babel 7 post also has a more in-depth answer.
Babel 7.4.0 or later (core-js 2 / 3)
As of Babel 7.4.0, #babel/polyfill is deprecated.
In general, there are two ways to install polyfills/regenerator: via global namespace (Option 1) or as ponyfill (Option 2, without global pollution).
Option 1: #babel/preset-env
presets: [
["#babel/preset-env", {
"useBuiltIns": "usage",
"corejs": 3, // or 2,
"targets": {
"firefox": "64", // or whatever target to choose .
},
}]
]
will automatically use regenerator-runtime and core-js according to your target. No need to import anything manually. Don't forget to install runtime dependencies:
npm i --save regenerator-runtime core-js
Alternatively, set useBuiltIns: "entry" and import it manually:
import "regenerator-runtime/runtime";
import "core-js/stable"; // if polyfills are also needed
Option 2: #babel/transform-runtime with #babel/runtime
This alternative has no global scope pollution and is suitable for libraries.
{
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"regenerator": true,
"corejs": 3 // or 2; if polyfills needed
...
}
]
]
}
Install it:
npm i -D #babel/plugin-transform-runtime
npm i #babel/runtime
If corejs polyfill is used, you replace #babel/runtime with #babel/runtime-corejs2 (for "corejs": 2) or #babel/runtime-corejs3 (for "corejs": 3).
Alternatively, if you don't need all the modules babel-polyfill provides, you can just specify babel-regenerator-runtime in your webpack config:
module.exports = {
entry: ['babel-regenerator-runtime', './test.js'],
// ...
};
When using webpack-dev-server with HMR, doing this reduced the number of files it has to compile on every build by quite a lot. This module is installed as part of babel-polyfill so if you already have that you're fine, otherwise you can install it separately with npm i -D babel-regenerator-runtime.
My simple solution:
npm install --save-dev babel-plugin-transform-runtime
npm install --save-dev babel-plugin-transform-async-to-generator
.babelrc
{
"presets": [
["latest", {
"es2015": {
"loose": true
}
}],
"react",
"stage-0"
],
"plugins": [
"transform-runtime",
"transform-async-to-generator"
]
}
This error is caused when async/await functions are used without the proper Babel plugins. As of March 2020, the following should be all you need to do. (#babel/polyfill and a lot of the accepted solutions have been deprecated in Babel. Read more in the Babel docs.)
In the command line, type:
npm install --save-dev #babel/plugin-transform-runtime
In your babel.config.js file, add this plugin #babel/plugin-transform-runtime. Note: The below example includes the other presets and plugins I have for a small React/Node/Express project I worked on recently:
module.exports = {
presets: ['#babel/preset-react', '#babel/preset-env'],
plugins: ['#babel/plugin-proposal-class-properties',
'#babel/plugin-transform-runtime'],
};
babel-regenerator-runtime is now deprecated, instead one should use regenerator-runtime.
To use the runtime generator with webpack and babel v7:
install regenerator-runtime:
npm i -D regenerator-runtime
And then add within webpack configuration :
entry: [
'regenerator-runtime/runtime',
YOUR_APP_ENTRY
]
Update your .babelrc file according to the following examples, it will work.
If you are using #babel/preset-env package
{
"presets": [
[
"#babel/preset-env", {
"targets": {
"node": "current"
}
}
]
]
}
or if you are using babel-preset-env package
{
"presets": [
[
"env", {
"targets": {
"node": "current"
}
}
]
]
}
As of Oct 2019 this worked for me:
Add this to the preset.
"presets": [
"#babel/preset-env"
]
Then install regenerator-runtime using npm.
npm i regenerator-runtime
And then in your main file use: (this import is used only once)
import "regenerator-runtime/runtime";
This is will enable you to use async awaits in your file and remove the regenerator error
Be careful of hoisted functions
I had both my 'polyfill import' and my 'async function' in the same file, however I was using the function syntax that hoists it above the polyfill which would give me the ReferenceError: regeneratorRuntime is not defined error.
Change this code
import "babel-polyfill"
async function myFunc(){ }
to this
import "babel-polyfill"
var myFunc = async function(){}
to prevent it being hoisted above the polyfill import.
If using babel-preset-stage-2 then just have to start the script with --require babel-polyfill.
In my case this error was thrown by Mocha tests.
Following fixed the issue
mocha \"server/tests/**/*.test.js\" --compilers js:babel-register --require babel-polyfill
I had this problem in Chrome. Similar to RienNeVaPlu͢s’s answer, this solved it for me:
npm install --save-dev regenerator-runtime
Then in my code:
import 'regenerator-runtime/runtime';
Happy to avoid the extra 200 kB from babel-polyfill.
I used tip from https://github.com/babel/babel/issues/9849#issuecomment-592668815 and added targets: { esmodules: true,} to my babel.config.js.
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
esmodules: true,
},
},
],
],
}
You're getting an error because async/await use generators, which are an ES2016 feature, not ES2015. One way to fix this is to install the babel preset for ES2016 (npm install --save babel-preset-es2016) and compile to ES2016 instead of ES2015:
"presets": [
"es2016",
// etc...
]
As the other answers mention, you can also use polyfills (though make sure you load the polyfill first before any other code runs). Alternatively, if you don't want to include all of the polyfill dependencies, you can use the babel-regenerator-runtime or the babel-plugin-transform-runtime.
I started getting this error after converting my project into a typescript project. From what I understand, the problem stems from async/await not being recognized.
For me the error was fixed by adding two things to my setup:
As mentioned above many times, I needed to add babel-polyfill into my webpack entry array:
...
entry: ['babel-polyfill', './index.js'],
...
I needed to update my .babelrc to allow the complilation of async/await into generators:
{
"presets": ["es2015"],
"plugins": ["transform-async-to-generator"]
}
DevDependencies:
I had to install a few things into my devDependencies in my package.json file as well. Namely, I was missing the babel-plugin-transform-async-to-generator, babel-polyfill and the babel-preset-es2015:
"devDependencies": {
"babel-loader": "^6.2.2",
"babel-plugin-transform-async-to-generator": "^6.5.0",
"babel-polyfill": "^6.5.0",
"babel-preset-es2015": "^6.5.0",
"webpack": "^1.12.13"
}
Full Code Gist:
I got the code from a really helpful and concise GitHub gist you can find here.
I fixed this error by installing babel-polyfill
npm install babel-polyfill --save
then I imported it in my app entry point
import http from 'http';
import config from 'dotenv';
import 'babel-polyfill';
import { register } from 'babel-core';
import app from '../app';
for testing I included --require babel-polyfill in my test script
"test": "export NODE_ENV=test|| SET NODE_ENV=test&& mocha --compilers
js:babel-core/register --require babel-polyfill server/test/**.js --exit"
There are so many answers up there, I will post my answer for my reference.
I use webpack and react, here is my solution without the .babelrc file
I am working on this in Aug 2020
Install react and babel
npm i #babel/core babel-loader #babel/preset-env #babel/preset-react react react-dom #babel/plugin-transform-runtime --save-dev
Then in my webpack.config.js
// other stuff
module.exports = {
// other stuff
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env',"#babel/preset-react"],
plugins: ['#babel/plugin-proposal-class-properties', '#babel/plugin-transform-runtime'],
//npm install --save-dev #babel/plugin-transform-runtime
}
}
},
],
},
};
I just don't know why I dont need to install the async package for the moment
New Answer Why you follow my answer ?
Ans: Because I am going to give you a answer with latest Update version npm project .
04/14/2017
"name": "es6",
"version": "1.0.0",
"babel-core": "^6.24.1",
"babel-loader": "^6.4.1",
"babel-polyfill": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"webpack": "^2.3.3",
"webpack-dev-server": "^2.4.2"
If your Use this version or more UP version of Npm and all other ...
SO just need to change :
webpack.config.js
module.exports = {
entry: ["babel-polyfill", "./app/js"]
};
After change webpack.config.js files Just add this line to top of your code .
import "babel-polyfill";
Now check everything is ok. Reference LINK
Also Thanks #BrunoLM for his nice Answer.
The targeted browsers I need to support already support async/await, but when writing mocha tests, without the proper setting I still got this error.
Most of the articles I googled are outdated, including the accepted answer and high voted answers here, i.e. you don't need polyfill, babel-regenerator-runtime, babel-plugin-transform-runtime. etc. if your target browser(s) already supports async/await (of course if not you need polyfill)
I don't want to use webpack either.
Tyler Long's answer is actually on the right track since he suggested babel-preset-env (but I omitted it first as he mentioned polifill at the beginning). I still got the ReferenceError: regeneratorRuntime is not defined at the first then I realized it was because I didn't set the target. After setting the target for node I fix the regeneratorRuntime error:
"scripts": {
//"test": "mocha --compilers js:babel-core/register"
//https://github.com/mochajs/mocha/wiki/compilers-deprecation
"test": "mocha --require babel-core/register"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-preset-env": "^1.7.0",
"mocha": "^5.2.0"
},
//better to set it .bablerc, I list it here for brevity and it works too.
"babel": {
"presets": [
["env",{
"targets": {
"node": "current"
"chrome": 66,
"firefox": 60,
},
"debug":true
}]
]
}
My working babel 7 boilerplate for react with regenerator runtime:
.babelrc
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": true,
},
},
],
"#babel/preset-react",
],
"plugins": [
"#babel/plugin-syntax-class-properties",
"#babel/plugin-proposal-class-properties"
]
}
package.json
...
"devDependencies": {
"#babel/core": "^7.0.0-0",
"#babel/plugin-proposal-class-properties": "^7.4.4",
"#babel/plugin-syntax-class-properties": "^7.2.0",
"#babel/polyfill": "^7.4.4",
"#babel/preset-env": "^7.4.5",
"#babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
...
main.js
import "#babel/polyfill";
....
Easiest way to fix this 'regeneratorRuntime not defined issue' in your console:
You don't have to install any unnecessary plugins. Just add:
<script src="https://unpkg.com/regenerator-runtime#0.13.1/runtime.js"></script>
inside of the body in your index.html.
Now regeneratorRuntime should be defined once you run babel and now your async/await functions should be compiled successfully into ES2015
Just install regenerator-runtime
with below command
npm i regenerator-runtime
add below line in startup file before you require server file
require("regenerator-runtime/runtime");
So far this has been working for me
I get this error using gulp with rollup when I tried to use ES6 generators:
gulp.task('scripts', () => {
return rollup({
entry: './app/scripts/main.js',
format: "iife",
sourceMap: true,
plugins: [babel({
exclude: 'node_modules/**',
"presets": [
[
"es2015-rollup"
]
],
"plugins": [
"external-helpers"
]
}),
includePaths({
include: {},
paths: ['./app/scripts'],
external: [],
extensions: ['.js']
})]
})
.pipe(source('app.js'))
.pipe(buffer())
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('.tmp/scripts'))
.pipe(reload({ stream: true }));
});
I may case the solution was to include babel-polyfill as bower component:
bower install babel-polyfill --save
and add it as dependency in index.html:
<script src="/bower_components/babel-polyfill/browser-polyfill.js"></script>
1 - Install babel-plugin-transform-async-to-module-method,
babel-polyfil, bluebird , babel-preset-es2015, babel-core :
npm install babel-plugin-transform-async-to-module-method babel-polyfill bluebird babel-preset-es2015 babel-core
2 - Add in your js babel polyfill:
import 'babel-polyfill';
3 - Add plugin in your .babelrc:
{
"presets": ["es2015"],
"plugins": [
["transform-async-to-module-method", {
"module": "bluebird",
"method": "coroutine"
}]
]
}
Source : http://babeljs.io/docs/plugins/transform-async-to-module-method/
For people looking to use the babel-polyfill version 7^ do this with webpack ver3^.
Npm install the module npm i -D #babel/polyfill
Then in your webpack file in your entry point do this
entry: ['#babel/polyfill', path.resolve(APP_DIR, 'App.js')],
To babel7 users and ParcelJS >= 1.10.0 users
npm i #babel/runtime-corejs2
npm i --save-dev #babel/plugin-transform-runtime #babel/core
.babelrc
{
"plugins": [
["#babel/plugin-transform-runtime", {
"corejs": 2
}]
]
}
taken from https://github.com/parcel-bundler/parcel/issues/1762
I had a setup
with webpack using presets: ['es2015', 'stage-0']
and mocha that was running tests compiled by webpack.
To make my async/await in tests work all I had to do is use mocha with the --require babel-polyfill option:
mocha --require babel-polyfill
I am using a React and Django project and got it to work by using regenerator-runtime. You should do this because #babel/polyfill will increase your app's size more and is also deprecated. I also followed this tutorial's episode 1 & 2 to create my project's structure.
*package.json*
...
"devDependencies": {
"regenerator-runtime": "^0.13.3",
...
}
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["transform-class-properties"]
}
index.js
...
import regeneratorRuntime from "regenerator-runtime";
import "regenerator-runtime/runtime";
ReactDOM.render(<App />, document.getElementById('app'));
...

Transpile ES6 Generators with Babel in the browser [duplicate]

I'm trying to use async/await from scratch on Babel 6, but I'm getting regeneratorRuntime is not defined.
.babelrc file
{
"presets": [ "es2015", "stage-0" ]
}
package.json file
"devDependencies": {
"babel-core": "^6.0.20",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.js file
"use strict";
async function foo() {
await bar();
}
function bar() { }
exports.default = foo;
Using it normally without the async/await works just fine. Any ideas what I'm doing wrong?
babel-polyfill (deprecated as of Babel 7.4) is required. You must also install it in order to get async/await working.
npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader
package.json
"devDependencies": {
"babel-core": "^6.0.20",
"babel-polyfill": "^6.0.16",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.babelrc
{
"presets": [ "es2015", "stage-0" ]
}
.js with async/await (sample code)
"use strict";
export default async function foo() {
var s = await bar();
console.log(s);
}
function bar() {
return "bar";
}
In the startup file
require("babel-core/register");
require("babel-polyfill");
If you are using webpack you need to put it as the first value of your entry array in your webpack configuration file (usually webpack.config.js), as per #Cemen comment:
module.exports = {
entry: ['babel-polyfill', './test.js'],
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel', }
]
}
};
If you want to run tests with babel then use:
mocha --compilers js:babel-core/register --require babel-polyfill
Note
If you're using babel 7, the package has been renamed to #babel/plugin-transform-runtime.
Besides polyfill, I use babel-plugin-transform-runtime. The plugin is described as:
Externalize references to helpers and builtins, automatically polyfilling your code without polluting globals. What does this actually mean though? Basically, you can use built-ins such as Promise, Set, Symbol etc as well use all the Babel features that require a polyfill seamlessly, without global pollution, making it extremely suitable for libraries.
It also includes support for async/await along with other built-ins of ES 6.
$ npm install --save-dev babel-plugin-transform-runtime
In .babelrc, add the runtime plugin
{
"plugins": [
["transform-runtime", {
"regenerator": true
}]
]
}
Babel 7 Users
I had some trouble getting around this since most information was for prior babel versions. For Babel 7, install 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"]
]
}
Update
It works if you set the target to Chrome. But it might not work for other targets, please refer to: https://github.com/babel/babel-preset-env/issues/112
So this answer is NOT quite proper for the original question. I will keep it here as a reference to babel-preset-env.
A simple solution is to add import 'babel-polyfill' at the beginning of your code.
If you use webpack, a quick solution is to add babel-polyfill as shown below:
entry: {
index: ['babel-polyfill', './index.js']
}
I believe I've found the latest best practice.
Check this project: https://github.com/babel/babel-preset-env
yarn add --dev babel-preset-env
Use the following as your babel configuration:
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 Chrome versions"]
}
}]
]
}
Then your app should be good to go in the last 2 versions of Chrome browser.
You can also set Node as the targets or fine-tune the browsers list according to https://github.com/ai/browserslist
Tell me what, don't tell me how.
I really like babel-preset-env's philosophy: tell me which environment you want to support, do NOT tell me how to support them. It's the beauty of declarative programming.
I've tested async await and they DO work. I don't know how they work and I really don't want to know. I want to spend my time on my own code and my business logic instead. Thanks to babel-preset-env, it liberates me from the Babel configuration hell.
Update: The Babel 7 post also has a more in-depth answer.
Babel 7.4.0 or later (core-js 2 / 3)
As of Babel 7.4.0, #babel/polyfill is deprecated.
In general, there are two ways to install polyfills/regenerator: via global namespace (Option 1) or as ponyfill (Option 2, without global pollution).
Option 1: #babel/preset-env
presets: [
["#babel/preset-env", {
"useBuiltIns": "usage",
"corejs": 3, // or 2,
"targets": {
"firefox": "64", // or whatever target to choose .
},
}]
]
will automatically use regenerator-runtime and core-js according to your target. No need to import anything manually. Don't forget to install runtime dependencies:
npm i --save regenerator-runtime core-js
Alternatively, set useBuiltIns: "entry" and import it manually:
import "regenerator-runtime/runtime";
import "core-js/stable"; // if polyfills are also needed
Option 2: #babel/transform-runtime with #babel/runtime
This alternative has no global scope pollution and is suitable for libraries.
{
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"regenerator": true,
"corejs": 3 // or 2; if polyfills needed
...
}
]
]
}
Install it:
npm i -D #babel/plugin-transform-runtime
npm i #babel/runtime
If corejs polyfill is used, you replace #babel/runtime with #babel/runtime-corejs2 (for "corejs": 2) or #babel/runtime-corejs3 (for "corejs": 3).
Alternatively, if you don't need all the modules babel-polyfill provides, you can just specify babel-regenerator-runtime in your webpack config:
module.exports = {
entry: ['babel-regenerator-runtime', './test.js'],
// ...
};
When using webpack-dev-server with HMR, doing this reduced the number of files it has to compile on every build by quite a lot. This module is installed as part of babel-polyfill so if you already have that you're fine, otherwise you can install it separately with npm i -D babel-regenerator-runtime.
My simple solution:
npm install --save-dev babel-plugin-transform-runtime
npm install --save-dev babel-plugin-transform-async-to-generator
.babelrc
{
"presets": [
["latest", {
"es2015": {
"loose": true
}
}],
"react",
"stage-0"
],
"plugins": [
"transform-runtime",
"transform-async-to-generator"
]
}
This error is caused when async/await functions are used without the proper Babel plugins. As of March 2020, the following should be all you need to do. (#babel/polyfill and a lot of the accepted solutions have been deprecated in Babel. Read more in the Babel docs.)
In the command line, type:
npm install --save-dev #babel/plugin-transform-runtime
In your babel.config.js file, add this plugin #babel/plugin-transform-runtime. Note: The below example includes the other presets and plugins I have for a small React/Node/Express project I worked on recently:
module.exports = {
presets: ['#babel/preset-react', '#babel/preset-env'],
plugins: ['#babel/plugin-proposal-class-properties',
'#babel/plugin-transform-runtime'],
};
babel-regenerator-runtime is now deprecated, instead one should use regenerator-runtime.
To use the runtime generator with webpack and babel v7:
install regenerator-runtime:
npm i -D regenerator-runtime
And then add within webpack configuration :
entry: [
'regenerator-runtime/runtime',
YOUR_APP_ENTRY
]
Update your .babelrc file according to the following examples, it will work.
If you are using #babel/preset-env package
{
"presets": [
[
"#babel/preset-env", {
"targets": {
"node": "current"
}
}
]
]
}
or if you are using babel-preset-env package
{
"presets": [
[
"env", {
"targets": {
"node": "current"
}
}
]
]
}
As of Oct 2019 this worked for me:
Add this to the preset.
"presets": [
"#babel/preset-env"
]
Then install regenerator-runtime using npm.
npm i regenerator-runtime
And then in your main file use: (this import is used only once)
import "regenerator-runtime/runtime";
This is will enable you to use async awaits in your file and remove the regenerator error
Be careful of hoisted functions
I had both my 'polyfill import' and my 'async function' in the same file, however I was using the function syntax that hoists it above the polyfill which would give me the ReferenceError: regeneratorRuntime is not defined error.
Change this code
import "babel-polyfill"
async function myFunc(){ }
to this
import "babel-polyfill"
var myFunc = async function(){}
to prevent it being hoisted above the polyfill import.
If using babel-preset-stage-2 then just have to start the script with --require babel-polyfill.
In my case this error was thrown by Mocha tests.
Following fixed the issue
mocha \"server/tests/**/*.test.js\" --compilers js:babel-register --require babel-polyfill
I had this problem in Chrome. Similar to RienNeVaPlu͢s’s answer, this solved it for me:
npm install --save-dev regenerator-runtime
Then in my code:
import 'regenerator-runtime/runtime';
Happy to avoid the extra 200 kB from babel-polyfill.
I used tip from https://github.com/babel/babel/issues/9849#issuecomment-592668815 and added targets: { esmodules: true,} to my babel.config.js.
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
esmodules: true,
},
},
],
],
}
You're getting an error because async/await use generators, which are an ES2016 feature, not ES2015. One way to fix this is to install the babel preset for ES2016 (npm install --save babel-preset-es2016) and compile to ES2016 instead of ES2015:
"presets": [
"es2016",
// etc...
]
As the other answers mention, you can also use polyfills (though make sure you load the polyfill first before any other code runs). Alternatively, if you don't want to include all of the polyfill dependencies, you can use the babel-regenerator-runtime or the babel-plugin-transform-runtime.
I started getting this error after converting my project into a typescript project. From what I understand, the problem stems from async/await not being recognized.
For me the error was fixed by adding two things to my setup:
As mentioned above many times, I needed to add babel-polyfill into my webpack entry array:
...
entry: ['babel-polyfill', './index.js'],
...
I needed to update my .babelrc to allow the complilation of async/await into generators:
{
"presets": ["es2015"],
"plugins": ["transform-async-to-generator"]
}
DevDependencies:
I had to install a few things into my devDependencies in my package.json file as well. Namely, I was missing the babel-plugin-transform-async-to-generator, babel-polyfill and the babel-preset-es2015:
"devDependencies": {
"babel-loader": "^6.2.2",
"babel-plugin-transform-async-to-generator": "^6.5.0",
"babel-polyfill": "^6.5.0",
"babel-preset-es2015": "^6.5.0",
"webpack": "^1.12.13"
}
Full Code Gist:
I got the code from a really helpful and concise GitHub gist you can find here.
I fixed this error by installing babel-polyfill
npm install babel-polyfill --save
then I imported it in my app entry point
import http from 'http';
import config from 'dotenv';
import 'babel-polyfill';
import { register } from 'babel-core';
import app from '../app';
for testing I included --require babel-polyfill in my test script
"test": "export NODE_ENV=test|| SET NODE_ENV=test&& mocha --compilers
js:babel-core/register --require babel-polyfill server/test/**.js --exit"
There are so many answers up there, I will post my answer for my reference.
I use webpack and react, here is my solution without the .babelrc file
I am working on this in Aug 2020
Install react and babel
npm i #babel/core babel-loader #babel/preset-env #babel/preset-react react react-dom #babel/plugin-transform-runtime --save-dev
Then in my webpack.config.js
// other stuff
module.exports = {
// other stuff
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env',"#babel/preset-react"],
plugins: ['#babel/plugin-proposal-class-properties', '#babel/plugin-transform-runtime'],
//npm install --save-dev #babel/plugin-transform-runtime
}
}
},
],
},
};
I just don't know why I dont need to install the async package for the moment
New Answer Why you follow my answer ?
Ans: Because I am going to give you a answer with latest Update version npm project .
04/14/2017
"name": "es6",
"version": "1.0.0",
"babel-core": "^6.24.1",
"babel-loader": "^6.4.1",
"babel-polyfill": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"webpack": "^2.3.3",
"webpack-dev-server": "^2.4.2"
If your Use this version or more UP version of Npm and all other ...
SO just need to change :
webpack.config.js
module.exports = {
entry: ["babel-polyfill", "./app/js"]
};
After change webpack.config.js files Just add this line to top of your code .
import "babel-polyfill";
Now check everything is ok. Reference LINK
Also Thanks #BrunoLM for his nice Answer.
The targeted browsers I need to support already support async/await, but when writing mocha tests, without the proper setting I still got this error.
Most of the articles I googled are outdated, including the accepted answer and high voted answers here, i.e. you don't need polyfill, babel-regenerator-runtime, babel-plugin-transform-runtime. etc. if your target browser(s) already supports async/await (of course if not you need polyfill)
I don't want to use webpack either.
Tyler Long's answer is actually on the right track since he suggested babel-preset-env (but I omitted it first as he mentioned polifill at the beginning). I still got the ReferenceError: regeneratorRuntime is not defined at the first then I realized it was because I didn't set the target. After setting the target for node I fix the regeneratorRuntime error:
"scripts": {
//"test": "mocha --compilers js:babel-core/register"
//https://github.com/mochajs/mocha/wiki/compilers-deprecation
"test": "mocha --require babel-core/register"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-preset-env": "^1.7.0",
"mocha": "^5.2.0"
},
//better to set it .bablerc, I list it here for brevity and it works too.
"babel": {
"presets": [
["env",{
"targets": {
"node": "current"
"chrome": 66,
"firefox": 60,
},
"debug":true
}]
]
}
My working babel 7 boilerplate for react with regenerator runtime:
.babelrc
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": true,
},
},
],
"#babel/preset-react",
],
"plugins": [
"#babel/plugin-syntax-class-properties",
"#babel/plugin-proposal-class-properties"
]
}
package.json
...
"devDependencies": {
"#babel/core": "^7.0.0-0",
"#babel/plugin-proposal-class-properties": "^7.4.4",
"#babel/plugin-syntax-class-properties": "^7.2.0",
"#babel/polyfill": "^7.4.4",
"#babel/preset-env": "^7.4.5",
"#babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
...
main.js
import "#babel/polyfill";
....
Easiest way to fix this 'regeneratorRuntime not defined issue' in your console:
You don't have to install any unnecessary plugins. Just add:
<script src="https://unpkg.com/regenerator-runtime#0.13.1/runtime.js"></script>
inside of the body in your index.html.
Now regeneratorRuntime should be defined once you run babel and now your async/await functions should be compiled successfully into ES2015
Just install regenerator-runtime
with below command
npm i regenerator-runtime
add below line in startup file before you require server file
require("regenerator-runtime/runtime");
So far this has been working for me
I get this error using gulp with rollup when I tried to use ES6 generators:
gulp.task('scripts', () => {
return rollup({
entry: './app/scripts/main.js',
format: "iife",
sourceMap: true,
plugins: [babel({
exclude: 'node_modules/**',
"presets": [
[
"es2015-rollup"
]
],
"plugins": [
"external-helpers"
]
}),
includePaths({
include: {},
paths: ['./app/scripts'],
external: [],
extensions: ['.js']
})]
})
.pipe(source('app.js'))
.pipe(buffer())
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('.tmp/scripts'))
.pipe(reload({ stream: true }));
});
I may case the solution was to include babel-polyfill as bower component:
bower install babel-polyfill --save
and add it as dependency in index.html:
<script src="/bower_components/babel-polyfill/browser-polyfill.js"></script>
1 - Install babel-plugin-transform-async-to-module-method,
babel-polyfil, bluebird , babel-preset-es2015, babel-core :
npm install babel-plugin-transform-async-to-module-method babel-polyfill bluebird babel-preset-es2015 babel-core
2 - Add in your js babel polyfill:
import 'babel-polyfill';
3 - Add plugin in your .babelrc:
{
"presets": ["es2015"],
"plugins": [
["transform-async-to-module-method", {
"module": "bluebird",
"method": "coroutine"
}]
]
}
Source : http://babeljs.io/docs/plugins/transform-async-to-module-method/
For people looking to use the babel-polyfill version 7^ do this with webpack ver3^.
Npm install the module npm i -D #babel/polyfill
Then in your webpack file in your entry point do this
entry: ['#babel/polyfill', path.resolve(APP_DIR, 'App.js')],
To babel7 users and ParcelJS >= 1.10.0 users
npm i #babel/runtime-corejs2
npm i --save-dev #babel/plugin-transform-runtime #babel/core
.babelrc
{
"plugins": [
["#babel/plugin-transform-runtime", {
"corejs": 2
}]
]
}
taken from https://github.com/parcel-bundler/parcel/issues/1762
I had a setup
with webpack using presets: ['es2015', 'stage-0']
and mocha that was running tests compiled by webpack.
To make my async/await in tests work all I had to do is use mocha with the --require babel-polyfill option:
mocha --require babel-polyfill
I am using a React and Django project and got it to work by using regenerator-runtime. You should do this because #babel/polyfill will increase your app's size more and is also deprecated. I also followed this tutorial's episode 1 & 2 to create my project's structure.
*package.json*
...
"devDependencies": {
"regenerator-runtime": "^0.13.3",
...
}
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["transform-class-properties"]
}
index.js
...
import regeneratorRuntime from "regenerator-runtime";
import "regenerator-runtime/runtime";
ReactDOM.render(<App />, document.getElementById('app'));
...

Babel 6 regeneratorRuntime is not defined

I'm trying to use async/await from scratch on Babel 6, but I'm getting regeneratorRuntime is not defined.
.babelrc file
{
"presets": [ "es2015", "stage-0" ]
}
package.json file
"devDependencies": {
"babel-core": "^6.0.20",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.js file
"use strict";
async function foo() {
await bar();
}
function bar() { }
exports.default = foo;
Using it normally without the async/await works just fine. Any ideas what I'm doing wrong?
babel-polyfill (deprecated as of Babel 7.4) is required. You must also install it in order to get async/await working.
npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader
package.json
"devDependencies": {
"babel-core": "^6.0.20",
"babel-polyfill": "^6.0.16",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.babelrc
{
"presets": [ "es2015", "stage-0" ]
}
.js with async/await (sample code)
"use strict";
export default async function foo() {
var s = await bar();
console.log(s);
}
function bar() {
return "bar";
}
In the startup file
require("babel-core/register");
require("babel-polyfill");
If you are using webpack you need to put it as the first value of your entry array in your webpack configuration file (usually webpack.config.js), as per #Cemen comment:
module.exports = {
entry: ['babel-polyfill', './test.js'],
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel', }
]
}
};
If you want to run tests with babel then use:
mocha --compilers js:babel-core/register --require babel-polyfill
Note
If you're using babel 7, the package has been renamed to #babel/plugin-transform-runtime.
Besides polyfill, I use babel-plugin-transform-runtime. The plugin is described as:
Externalize references to helpers and builtins, automatically polyfilling your code without polluting globals. What does this actually mean though? Basically, you can use built-ins such as Promise, Set, Symbol etc as well use all the Babel features that require a polyfill seamlessly, without global pollution, making it extremely suitable for libraries.
It also includes support for async/await along with other built-ins of ES 6.
$ npm install --save-dev babel-plugin-transform-runtime
In .babelrc, add the runtime plugin
{
"plugins": [
["transform-runtime", {
"regenerator": true
}]
]
}
Babel 7 Users
I had some trouble getting around this since most information was for prior babel versions. For Babel 7, install 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"]
]
}
Update
It works if you set the target to Chrome. But it might not work for other targets, please refer to: https://github.com/babel/babel-preset-env/issues/112
So this answer is NOT quite proper for the original question. I will keep it here as a reference to babel-preset-env.
A simple solution is to add import 'babel-polyfill' at the beginning of your code.
If you use webpack, a quick solution is to add babel-polyfill as shown below:
entry: {
index: ['babel-polyfill', './index.js']
}
I believe I've found the latest best practice.
Check this project: https://github.com/babel/babel-preset-env
yarn add --dev babel-preset-env
Use the following as your babel configuration:
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 Chrome versions"]
}
}]
]
}
Then your app should be good to go in the last 2 versions of Chrome browser.
You can also set Node as the targets or fine-tune the browsers list according to https://github.com/ai/browserslist
Tell me what, don't tell me how.
I really like babel-preset-env's philosophy: tell me which environment you want to support, do NOT tell me how to support them. It's the beauty of declarative programming.
I've tested async await and they DO work. I don't know how they work and I really don't want to know. I want to spend my time on my own code and my business logic instead. Thanks to babel-preset-env, it liberates me from the Babel configuration hell.
Update: The Babel 7 post also has a more in-depth answer.
Babel 7.4.0 or later (core-js 2 / 3)
As of Babel 7.4.0, #babel/polyfill is deprecated.
In general, there are two ways to install polyfills/regenerator: via global namespace (Option 1) or as ponyfill (Option 2, without global pollution).
Option 1: #babel/preset-env
presets: [
["#babel/preset-env", {
"useBuiltIns": "usage",
"corejs": 3, // or 2,
"targets": {
"firefox": "64", // or whatever target to choose .
},
}]
]
will automatically use regenerator-runtime and core-js according to your target. No need to import anything manually. Don't forget to install runtime dependencies:
npm i --save regenerator-runtime core-js
Alternatively, set useBuiltIns: "entry" and import it manually:
import "regenerator-runtime/runtime";
import "core-js/stable"; // if polyfills are also needed
Option 2: #babel/transform-runtime with #babel/runtime
This alternative has no global scope pollution and is suitable for libraries.
{
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"regenerator": true,
"corejs": 3 // or 2; if polyfills needed
...
}
]
]
}
Install it:
npm i -D #babel/plugin-transform-runtime
npm i #babel/runtime
If corejs polyfill is used, you replace #babel/runtime with #babel/runtime-corejs2 (for "corejs": 2) or #babel/runtime-corejs3 (for "corejs": 3).
Alternatively, if you don't need all the modules babel-polyfill provides, you can just specify babel-regenerator-runtime in your webpack config:
module.exports = {
entry: ['babel-regenerator-runtime', './test.js'],
// ...
};
When using webpack-dev-server with HMR, doing this reduced the number of files it has to compile on every build by quite a lot. This module is installed as part of babel-polyfill so if you already have that you're fine, otherwise you can install it separately with npm i -D babel-regenerator-runtime.
My simple solution:
npm install --save-dev babel-plugin-transform-runtime
npm install --save-dev babel-plugin-transform-async-to-generator
.babelrc
{
"presets": [
["latest", {
"es2015": {
"loose": true
}
}],
"react",
"stage-0"
],
"plugins": [
"transform-runtime",
"transform-async-to-generator"
]
}
This error is caused when async/await functions are used without the proper Babel plugins. As of March 2020, the following should be all you need to do. (#babel/polyfill and a lot of the accepted solutions have been deprecated in Babel. Read more in the Babel docs.)
In the command line, type:
npm install --save-dev #babel/plugin-transform-runtime
In your babel.config.js file, add this plugin #babel/plugin-transform-runtime. Note: The below example includes the other presets and plugins I have for a small React/Node/Express project I worked on recently:
module.exports = {
presets: ['#babel/preset-react', '#babel/preset-env'],
plugins: ['#babel/plugin-proposal-class-properties',
'#babel/plugin-transform-runtime'],
};
babel-regenerator-runtime is now deprecated, instead one should use regenerator-runtime.
To use the runtime generator with webpack and babel v7:
install regenerator-runtime:
npm i -D regenerator-runtime
And then add within webpack configuration :
entry: [
'regenerator-runtime/runtime',
YOUR_APP_ENTRY
]
Update your .babelrc file according to the following examples, it will work.
If you are using #babel/preset-env package
{
"presets": [
[
"#babel/preset-env", {
"targets": {
"node": "current"
}
}
]
]
}
or if you are using babel-preset-env package
{
"presets": [
[
"env", {
"targets": {
"node": "current"
}
}
]
]
}
As of Oct 2019 this worked for me:
Add this to the preset.
"presets": [
"#babel/preset-env"
]
Then install regenerator-runtime using npm.
npm i regenerator-runtime
And then in your main file use: (this import is used only once)
import "regenerator-runtime/runtime";
This is will enable you to use async awaits in your file and remove the regenerator error
Be careful of hoisted functions
I had both my 'polyfill import' and my 'async function' in the same file, however I was using the function syntax that hoists it above the polyfill which would give me the ReferenceError: regeneratorRuntime is not defined error.
Change this code
import "babel-polyfill"
async function myFunc(){ }
to this
import "babel-polyfill"
var myFunc = async function(){}
to prevent it being hoisted above the polyfill import.
If using babel-preset-stage-2 then just have to start the script with --require babel-polyfill.
In my case this error was thrown by Mocha tests.
Following fixed the issue
mocha \"server/tests/**/*.test.js\" --compilers js:babel-register --require babel-polyfill
I had this problem in Chrome. Similar to RienNeVaPlu͢s’s answer, this solved it for me:
npm install --save-dev regenerator-runtime
Then in my code:
import 'regenerator-runtime/runtime';
Happy to avoid the extra 200 kB from babel-polyfill.
I used tip from https://github.com/babel/babel/issues/9849#issuecomment-592668815 and added targets: { esmodules: true,} to my babel.config.js.
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
esmodules: true,
},
},
],
],
}
You're getting an error because async/await use generators, which are an ES2016 feature, not ES2015. One way to fix this is to install the babel preset for ES2016 (npm install --save babel-preset-es2016) and compile to ES2016 instead of ES2015:
"presets": [
"es2016",
// etc...
]
As the other answers mention, you can also use polyfills (though make sure you load the polyfill first before any other code runs). Alternatively, if you don't want to include all of the polyfill dependencies, you can use the babel-regenerator-runtime or the babel-plugin-transform-runtime.
I started getting this error after converting my project into a typescript project. From what I understand, the problem stems from async/await not being recognized.
For me the error was fixed by adding two things to my setup:
As mentioned above many times, I needed to add babel-polyfill into my webpack entry array:
...
entry: ['babel-polyfill', './index.js'],
...
I needed to update my .babelrc to allow the complilation of async/await into generators:
{
"presets": ["es2015"],
"plugins": ["transform-async-to-generator"]
}
DevDependencies:
I had to install a few things into my devDependencies in my package.json file as well. Namely, I was missing the babel-plugin-transform-async-to-generator, babel-polyfill and the babel-preset-es2015:
"devDependencies": {
"babel-loader": "^6.2.2",
"babel-plugin-transform-async-to-generator": "^6.5.0",
"babel-polyfill": "^6.5.0",
"babel-preset-es2015": "^6.5.0",
"webpack": "^1.12.13"
}
Full Code Gist:
I got the code from a really helpful and concise GitHub gist you can find here.
I fixed this error by installing babel-polyfill
npm install babel-polyfill --save
then I imported it in my app entry point
import http from 'http';
import config from 'dotenv';
import 'babel-polyfill';
import { register } from 'babel-core';
import app from '../app';
for testing I included --require babel-polyfill in my test script
"test": "export NODE_ENV=test|| SET NODE_ENV=test&& mocha --compilers
js:babel-core/register --require babel-polyfill server/test/**.js --exit"
There are so many answers up there, I will post my answer for my reference.
I use webpack and react, here is my solution without the .babelrc file
I am working on this in Aug 2020
Install react and babel
npm i #babel/core babel-loader #babel/preset-env #babel/preset-react react react-dom #babel/plugin-transform-runtime --save-dev
Then in my webpack.config.js
// other stuff
module.exports = {
// other stuff
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env',"#babel/preset-react"],
plugins: ['#babel/plugin-proposal-class-properties', '#babel/plugin-transform-runtime'],
//npm install --save-dev #babel/plugin-transform-runtime
}
}
},
],
},
};
I just don't know why I dont need to install the async package for the moment
New Answer Why you follow my answer ?
Ans: Because I am going to give you a answer with latest Update version npm project .
04/14/2017
"name": "es6",
"version": "1.0.0",
"babel-core": "^6.24.1",
"babel-loader": "^6.4.1",
"babel-polyfill": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"webpack": "^2.3.3",
"webpack-dev-server": "^2.4.2"
If your Use this version or more UP version of Npm and all other ...
SO just need to change :
webpack.config.js
module.exports = {
entry: ["babel-polyfill", "./app/js"]
};
After change webpack.config.js files Just add this line to top of your code .
import "babel-polyfill";
Now check everything is ok. Reference LINK
Also Thanks #BrunoLM for his nice Answer.
The targeted browsers I need to support already support async/await, but when writing mocha tests, without the proper setting I still got this error.
Most of the articles I googled are outdated, including the accepted answer and high voted answers here, i.e. you don't need polyfill, babel-regenerator-runtime, babel-plugin-transform-runtime. etc. if your target browser(s) already supports async/await (of course if not you need polyfill)
I don't want to use webpack either.
Tyler Long's answer is actually on the right track since he suggested babel-preset-env (but I omitted it first as he mentioned polifill at the beginning). I still got the ReferenceError: regeneratorRuntime is not defined at the first then I realized it was because I didn't set the target. After setting the target for node I fix the regeneratorRuntime error:
"scripts": {
//"test": "mocha --compilers js:babel-core/register"
//https://github.com/mochajs/mocha/wiki/compilers-deprecation
"test": "mocha --require babel-core/register"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-preset-env": "^1.7.0",
"mocha": "^5.2.0"
},
//better to set it .bablerc, I list it here for brevity and it works too.
"babel": {
"presets": [
["env",{
"targets": {
"node": "current"
"chrome": 66,
"firefox": 60,
},
"debug":true
}]
]
}
My working babel 7 boilerplate for react with regenerator runtime:
.babelrc
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": true,
},
},
],
"#babel/preset-react",
],
"plugins": [
"#babel/plugin-syntax-class-properties",
"#babel/plugin-proposal-class-properties"
]
}
package.json
...
"devDependencies": {
"#babel/core": "^7.0.0-0",
"#babel/plugin-proposal-class-properties": "^7.4.4",
"#babel/plugin-syntax-class-properties": "^7.2.0",
"#babel/polyfill": "^7.4.4",
"#babel/preset-env": "^7.4.5",
"#babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
...
main.js
import "#babel/polyfill";
....
Easiest way to fix this 'regeneratorRuntime not defined issue' in your console:
You don't have to install any unnecessary plugins. Just add:
<script src="https://unpkg.com/regenerator-runtime#0.13.1/runtime.js"></script>
inside of the body in your index.html.
Now regeneratorRuntime should be defined once you run babel and now your async/await functions should be compiled successfully into ES2015
Just install regenerator-runtime
with below command
npm i regenerator-runtime
add below line in startup file before you require server file
require("regenerator-runtime/runtime");
So far this has been working for me
I get this error using gulp with rollup when I tried to use ES6 generators:
gulp.task('scripts', () => {
return rollup({
entry: './app/scripts/main.js',
format: "iife",
sourceMap: true,
plugins: [babel({
exclude: 'node_modules/**',
"presets": [
[
"es2015-rollup"
]
],
"plugins": [
"external-helpers"
]
}),
includePaths({
include: {},
paths: ['./app/scripts'],
external: [],
extensions: ['.js']
})]
})
.pipe(source('app.js'))
.pipe(buffer())
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('.tmp/scripts'))
.pipe(reload({ stream: true }));
});
I may case the solution was to include babel-polyfill as bower component:
bower install babel-polyfill --save
and add it as dependency in index.html:
<script src="/bower_components/babel-polyfill/browser-polyfill.js"></script>
1 - Install babel-plugin-transform-async-to-module-method,
babel-polyfil, bluebird , babel-preset-es2015, babel-core :
npm install babel-plugin-transform-async-to-module-method babel-polyfill bluebird babel-preset-es2015 babel-core
2 - Add in your js babel polyfill:
import 'babel-polyfill';
3 - Add plugin in your .babelrc:
{
"presets": ["es2015"],
"plugins": [
["transform-async-to-module-method", {
"module": "bluebird",
"method": "coroutine"
}]
]
}
Source : http://babeljs.io/docs/plugins/transform-async-to-module-method/
For people looking to use the babel-polyfill version 7^ do this with webpack ver3^.
Npm install the module npm i -D #babel/polyfill
Then in your webpack file in your entry point do this
entry: ['#babel/polyfill', path.resolve(APP_DIR, 'App.js')],
To babel7 users and ParcelJS >= 1.10.0 users
npm i #babel/runtime-corejs2
npm i --save-dev #babel/plugin-transform-runtime #babel/core
.babelrc
{
"plugins": [
["#babel/plugin-transform-runtime", {
"corejs": 2
}]
]
}
taken from https://github.com/parcel-bundler/parcel/issues/1762
I had a setup
with webpack using presets: ['es2015', 'stage-0']
and mocha that was running tests compiled by webpack.
To make my async/await in tests work all I had to do is use mocha with the --require babel-polyfill option:
mocha --require babel-polyfill
I am using a React and Django project and got it to work by using regenerator-runtime. You should do this because #babel/polyfill will increase your app's size more and is also deprecated. I also followed this tutorial's episode 1 & 2 to create my project's structure.
*package.json*
...
"devDependencies": {
"regenerator-runtime": "^0.13.3",
...
}
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["transform-class-properties"]
}
index.js
...
import regeneratorRuntime from "regenerator-runtime";
import "regenerator-runtime/runtime";
ReactDOM.render(<App />, document.getElementById('app'));
...

How to use ESLint with Jest

I'm attempting to use the ESLint linter with the Jest testing framework.
Jest tests run with some globals like jest, which I'll need to tell the linter about; but the tricky thing is the directory structure, with Jest the tests are embedded with the source code in __tests__ folders, so the directory structure looks something like:
src
foo
foo.js
__tests__
fooTest.js
bar
bar.js
__tests__
barTest.js
Normally, I'd have all my tests under a single dir, and I could just add an .eslintrc file there to add the globals... but I certainly don't want to add a .eslintrc file to every single __test__ dir.
For now, I've just added the test globals to the global .eslintrc file, but since that means I could now reference jest in non-testing code, that doesn't seem like the "right" solution.
Is there a way to get eslint to apply rules based on some pattern based on the directory name, or something like that?
The docs show you are now able to add:
"env": {
"jest/globals": true
}
To your .eslintrc which will add all the jest related things to your environment, eliminating the linter errors/warnings.
You may need to include plugins: ["jest"] to your esconfig, and add the eslint-plugin-jest plugin if it still isn't working.
ESLint supports this as of version >= 4:
/*
.eslintrc.js
*/
const ERROR = 2;
const WARN = 1;
module.exports = {
extends: "eslint:recommended",
env: {
es6: true
},
overrides: [
{
files: [
"**/*.test.js"
],
env: {
jest: true // now **/*.test.js files' env has both es6 *and* jest
},
// Can't extend in overrides: https://github.com/eslint/eslint/issues/8813
// "extends": ["plugin:jest/recommended"]
plugins: ["jest"],
rules: {
"jest/no-disabled-tests": "warn",
"jest/no-focused-tests": "error",
"jest/no-identical-title": "error",
"jest/prefer-to-have-length": "warn",
"jest/valid-expect": "error"
}
}
],
};
Here is a workaround (from another answer on here, vote it up!) for the "extend in overrides" limitation of eslint config :
overrides: [
Object.assign(
{
files: [ '**/*.test.js' ],
env: { jest: true },
plugins: [ 'jest' ],
},
require('eslint-plugin-jest').configs.recommended
)
]
From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724
You can also set the test env in your test file as follows:
/* eslint-env jest */
describe(() => {
/* ... */
})
To complete Zachary's answer, here is a workaround for the "extend in overrides" limitation of eslint config :
overrides: [
Object.assign(
{
files: [ '**/*.test.js' ],
env: { jest: true },
plugins: [ 'jest' ],
},
require('eslint-plugin-jest').configs.recommended
)
]
From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724
As of 2021, I think the correct way or at least the one that works is to install #types/jest and eslint-plugin-jest:
npm i -D eslint-plugin-jest #types/jest
And adding the Jest plugin into .eslintrc.js with the overrides instruction mentioned by #Loren:
module.exports = {
...
plugins: ["jest"],
...
overrides: [
{
files: ["**/*.test.js"],
env: { "jest/globals": true },
plugins: ["jest"],
extends: ["plugin:jest/recommended"],
},
],
...
};
This way you get linting errors in your source files as well as in test files, but in test files you don't get linting errors for test and other Jest's functions, but you will get them in your source files as they will appear as undefined there.
I solved the problem REF
Run
# For Yarn
yarn add eslint-plugin-jest -D
# For NPM
npm i eslint-plugin-jest -D
And then add in your .eslintrc file
{
"extends": ["airbnb","plugin:jest/recommended"],
}
some of the answers assume you have eslint-plugin-jest installed, however without needing to do that, you can simply do this in your .eslintrc file, add:
"globals": {
"jest": true,
}
First install eslint-plugin-jest
Running:
yarn add eslint-plugin-jest or npm install eslint-plugin-jest
Then edit .eslintrc.json
{
"env":{
"jest": true
}
}
As of ESLint V 6 (released in late 2019), you can use extends in the glob based config as follows:
"overrides": [
{
"files": ["*.test.js"],
"env": {
"jest": true
},
"plugins": ["jest"],
"extends": ["plugin:jest/recommended"]
}
]
Add environment only for __tests__ folder
You could add a .eslintrc.yml file in your __tests__ folders, that extends you basic configuration:
extends: <relative_path to .eslintrc>
env:
jest: true
If you have only one __tests__folder, this solution is the best since it scope jest environment only where it is needed.
Dealing with many test folders
If you have more test folders (OPs case), I'd still suggest to add those files. And if you have tons of those folders can add them with a simple zsh script:
#!/usr/bin/env zsh
for folder in **/__tests__/ ;do
count=$(($(tr -cd '/' <<< $folder | wc -c)))
echo $folder : $count
cat <<EOF > $folder.eslintrc.yml
extends: $(printf '../%.0s' {1..$count}).eslintrc
env:
jest: true
EOF
done
This script will look for __tests__ folders and add a .eslintrc.yml file with to configuration shown above. This script has to be launched within the folder containing your parent .eslintrc.
Pattern based configs are scheduled for 2.0.0 release of ESLint. For now, however, you will have to create two separate tasks (as mentioned in the comments). One for tests and one for the rest of the code and run both of them, while providing different .eslintrc files.
P.S. There's a jest environment coming in the next release of ESLint, it will register all of the necessary globals.
I got it running after spending some time trying out different options. Hope this helps anyone else getting stuck.
.eslintrc.json (in root project folder):
{
"env": {
"browser": true,
"es2021": true,
"jest/globals": true
},
"extends": [
"standard",
"plugin:jest/all"
],
"parser": "#babel/eslint-parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
"jest/no-hooks": [
"error",
{
"allow": [
"afterEach",
"beforeEach"
]
}
]
},
"plugins": [
"jest"
]
}
Empty .babelrc (in root project folder):
{}
.package.json (in root project folder):
{
"scripts": {
"test": "jest",
"lint": "npx eslint --format=table .",
"lintfix": "npx eslint --fix ."
},
"devDependencies": {
"#babel/core": "^7.15.0",
"#babel/eslint-parser": "^7.15.0",
"aws-sdk-mock": "^5.2.1",
"eslint": "^7.32.0",
"eslint-config-standard": "^16.0.3",
"eslint-plugin-import": "^2.24.0",
"eslint-plugin-jest": "^24.4.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^5.1.0",
"jest": "^27.0.6"
}
}
VS Code settings.xml (editor configuration: enables auto fix on save + babel parser):
"eslint.alwaysShowStatus": true,
"eslint.format.enable": true,
"eslint.lintTask.enable": true,
"eslint.options": {
"parser": "#babel/eslint-parser"
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": [
"javascript"
]
In your .eslintignore file add the following value:
**/__tests__/
This should ignore all instances of the __tests__ directory and their children.

Categories