Related
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'));
...
I have a monorepo structure of my project like this:
babel.config.js
a-something
b-something
where I have the babel config file in the root of my project and the packages a-something and b-something.
Inside package a-something I have the following webpack config:
const path = require('path')
module.exports = {
target: 'node',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.js?$/,
use: {
loader: 'babel-loader',
options: {
rootMode: 'upward'
}
},
include: [
path.resolve(__dirname, 'src'),
/node_modules\/a-/,
/node_modules\/b-/
]
}
]
}
}
Inside the package a-something I have the following package.json:
{
"name": "a-something",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"prod:build": "webpack --config webpack.config.js",
"prod:start": "node build/bundle.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.2",
"graphql": "^14.5.8",
"graphql-request": "^1.8.2",
"graphql-tag": "^2.10.1",
"b-something": "^1.0.0",
"node-fetch": "^2.6.0",
"sitemap": "^5.0.0"
},
"devDependencies": {
"webpack": "3.5.6",
"#babel/polyfill": "7.7.0"
}
}
My root package.json has the following dependencies:
"#babel/cli": "^7.5.5",
"#babel/core": "^7.5.5",
"babel-loader": "8.0.6"
and lastly my Dockerfile inside package a-something is:
FROM node:10.15.1
COPY ./package.json /src/package.json
ENV PORT 3000
ENV NODE_ENV production
WORKDIR /src
RUN npm install
COPY ./lerna.json /src/lerna.json
COPY ./packages/a-something/package.json /src/packages/a-something/package.json
COPY ./packages/b-something/package.json /src/packages/b-something/package.json
RUN npm run clean
COPY . /src
WORKDIR /src/packages/a-something
RUN npm run prod:build
RUN echo "FINISHED BUILDING!"
EXPOSE ${PORT}
CMD ["npm" , "run", "prod:start"]
When I run npm run prod: build and npm run prod: start the bundle is built successfully, however when I build the docker (where the context is the root folder) I get the following npm error:
ERROR in Entry module not found: Error: Can't resolve 'babel-loader' in '/src/packages/a-something'
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! a-something#1.0.0 prod:build: `webpack --config webpack.config.js`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the a-something#1.0.0 prod:build script.
My host machine OS is macOS Mojave. Maybe the symlinks generated by Lerna are handled differently on Debian (used by node image)?
UPDATE: the issue was resolved by moving all babel related npm packages from devDependencies to dependencies section of root package.json. Does anyone have an idea why this would solve the problem?
As I mentioned in the update section of my question the solution was to move all babel related packages to devDependencies section of the root package.json.
But why did this help?
The problem was I set NODE_ENV to production in Dockerfile. npm will not install dev dependencies if NODE_ENV is set to production. On the host machine I didn't have such variable. In addition another issue would've been #babel/polyfill, according to babel docs:
Because this is a polyfill (which will run before your source code),
we need it to be a dependency, not a devDependency
According to the docs #babel/polyfill is also deprecated so the better solution is to:
add "babel-loader": "8.0.6" to root package.json
Have the following devDependencies in a-something package.json:
"devDependencies": {
"webpack": "3.5.6",
"core-js": "^3.4.7",
"regenerator-runtime": "^0.13.3"
}
Place these 2 lines in the entry Javascript file at the very top:
import 'core-js/stable'
import 'regenerator-runtime/runtime'
Finally use this webpack config:
const path = require('path')
module.exports = {
target: 'node',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
module: {
rules: [
{
test: /\.js?$/,
use: {
loader: 'babel-loader',
options: {
rootMode: 'upward',
presets: [
['#babel/preset-env', {
corejs: 3,
useBuiltIns: 'usage'
}]
]
}
},
include: [
path.resolve(__dirname, 'src'),
/node_modules\/a-/,
/node_modules\/b-/
]
}
]
}
}
I have an application that is a node backend and a react frontend.
I get the following error when i try to build/run my node application.
Node: v10.13.0
Error:
dist/index.js:314
regeneratorRuntime.mark(function _callee(productId) {
^
ReferenceError: regeneratorRuntime is not defined
.babelrc
{
"presets": [ [
"#babel/preset-env", {
"targets": {
"node": "current"
},
}
], "#babel/preset-react"],
"plugins": [
"#babel/plugin-proposal-class-properties"
]
}
webpack.config.js
{
mode: "development",
entry: "./src/index.js",
target: "node",
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
stats: {
colors: true
},
devtool: "source-map",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.js",
sourceMapFilename: "index.js.map"
},
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
},
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
}
],
},
node: {
__dirname: false,
__filename: false,
},
"plugins": [
new CleanWebpackPlugin(),
new WebpackShellPlugin({
onBuildStart: [],
onBuildEnd: ["nodemon dist/index.js"]
}),
]
},
package.json
"dependencies": {
"connect": "^3.6.6",
"cors": "^2.8.5",
"dotenv": "^6.1.0",
"express": "^4.16.4",
"hellojs": "^1.17.1",
"i18n-iso-countries": "^3.7.8",
"morgan": "^1.9.1",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"request": "^2.88.0",
"request-promise-native": "^1.0.5",
"serve-static": "^1.13.2",
"vhost": "^3.0.2"
},
"devDependencies": {
"#babel/cli": "^7.1.5",
"#babel/core": "^7.1.6",
"#babel/plugin-proposal-class-properties": "^7.1.0",
"#babel/preset-env": "^7.1.6",
"#babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.4",
"clean-webpack-plugin": "^1.0.0",
"copy-webpack-plugin": "^4.6.0",
"css-loader": "^1.0.1",
"eslint": "^5.9.0",
"eslint-config-google": "^0.10.0",
"eslint-loader": "^2.1.1",
"eslint-plugin-react": "^7.11.1",
"extract-loader": "^3.0.0",
"file-loader": "^2.0.0",
"node-sass": "^4.10.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.26.0",
"webpack-cli": "^3.1.2",
"webpack-node-externals": "^1.7.2",
"webpack-shell-plugin": "^0.5.0"
}
Updated Answer:
If you are using Babel 7.4.0 or newer, then #babel/polyfill has been deprecated. Instead, you will want to use the following at the top of your main js file (likely index.js or similar):
import "core-js/stable";
import "regenerator-runtime/runtime";
Install these packages either with npm:
npm install --save core-js
npm install --save regenerator-runtime
or with yarn:
yarn add core-js
yarn add regenerator-runtime
Original Answer:
I just encountered this problem and came across the following solution:
In package.json I had #babel/polyfill as a dependency. However, in my index.js (My main js file) I had neglected to place the following line at the the top:
import '#babel/polyfill'
Once I imported it, everything worked fine.
I did not need to install babel-runtime as other answers are suggesting.
Babel 7.4.0 and later
There are two main configurations - one for apps and one for libraries.
Option 1: App
When to use: ✔ for applications ✔ global scope polyfills ✔ smallest bundle size ✔ selective inclusion via targets ✔ No need to process node_modules for polyfills
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "usage", // alternative mode: "entry"
"corejs": 3, // default would be 2
"targets": "> 0.25%, not dead"
// set your own target environment here (see Browserslist)
}
]
]
Install dependencies:
npm i --save-dev #babel/preset-env
npm i regenerator-runtime core-js // run-time dependencies
// regenerator-runtime: transform (async) generators and `async`/`await`
// core-js: other ECMAScript features like Promise, Set, etc.
#babel/preset-env selectively includes polyfills for targets, specified by a Browserslist query. There are two modes - try usage first (more convenient), else entry (more flexible and robust):
useBuiltIns 'usage': no need to import anything manually. All polyfills are added automatically based on their code usage in a file.
useBuiltIns 'entry': Add these import entries once (!) in your app - akin to #babel/polyfill:
import "regenerator-runtime/runtime";
import "core-js/stable"; // or more selective import, like "core-js/es/array"
Extension
For advanced cases, you might use #babel/transform-runtime (dev) and #babel/runtime (run-time) only for Babel helpers to reduce bundle size a bit more - called helper aliasing.
Option 2: Library
When to use: ✔ for libraries ✔ no global scope pollution ✔ includes all polyfills, not selective ✔ bigger bundle size neglectable
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"regenerator": true,
"corejs": 3
}
]
]
Install compile-time and run-time dependencies:
npm i --save-dev #babel/plugin-transform-runtime // only for build phase
npm i #babel/runtime // runtime babel helpers + just regenerator runtime
// OR (choose one!)
npm i #babel/runtime-corejs3
// also contains other JS polyfills (not only regenerator runtime)
// depends on core-js-pure ("ponyfills"/polyfills that don't pollute global scope)
See #babel/plugin-transform-runtime, #babel/runtime, #babel/runtime-corejs.
Extension
You can additionally use #babel/preset-env for syntax transpilation only, with useBuiltIns: false. As the library option does not use global polyfills, you might want to transpile node_modules as well - see the absoluteRuntime option.
Closing notes
Breaking Change: #babel/polyfill is deprecated starting with Babel 7.4.0.
Legacy: If you can't switch to core-js#3, set corejs option to 2 (see migrations). Install #babel/runtime-corejs2 in case of option 2 (#babel/plugin-transform-runtime).
Excellent summary in #9853 by Jovica Markoski
Currently, the library approach doesn't take selective targets into account - meaning you take locally scoped polyfills at the price of bigger bundle size (including all polyfills).
babel-polyfills is a new, experimental approach to inject different polyfills (not just core-js) with different strategies.
This also allows to selectively include locally scoped polyfills.
There is already a very good answer here (originally posted on the Babel6 question) which I will just translate to Yarn. Basically, you need babel runtime (NOT as a dev dependency) and the plugin transform-runtime
yarn add #babel/runtime
yarn add -D #babel/plugin-transform-runtime
And, in .babelrc, add:
{
"presets": ["#babel/preset-env"],
"plugins": ["#babel/transform-runtime"]
}
I had this error in my react project with webpack 4 and this was preventing the whole project to get rendered.
This is how I solved it:
Install plugin-transform-runtime:
npm install #babel/plugin-transform-runtime -D
Add plugin-transform-runtime to the plugin's list in the .babelrc file:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
["#babel/transform-runtime"] // <= Add it here
]
}
For me worked:
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
esmodules: true,
},
},
],
],
}
I just solved this error when I imported babel-polyfill directly into the file that shows the error, for example, the error says "ReferenceError: regeneratorRuntime is not defined at /dist/models/usersSchema.js", so I use this in my usersSchema.js file:
require("babel-polyfill");
(you can use import "babel-polyfill";as well)
You will need to have the regeneratorRuntime.
Install this two packages - babel-plugin-transform-regenerator and babel-polyfill
Add the following Babel configuration via .babelrc
{
"plugins": ["transform-regenerator"]
}
React.js Users
If this issue faced you while using react (specifically while trying to use Async/Wait), then Valentino Gagliardi provided a detailed approach on his blog regarding how to address this issue
How to use ES6 in webpack.config ?
Like this repo
https://github.com/kriasoft/react-starter-kit
does ?
For instance:
using this
import webpack from 'webpack';
instead of
var webpack = require('webpack');
It is quite a curiosity rather than a need.
Try naming your config as webpack.config.babel.js. You should have babel-register included in the project. Example at react-router-bootstrap.
Webpack relies on interpret internally to make this work.
As an alternative to what #bebraw suggests, you can create a JavaScript automation script with ES6+ syntax:
// tools/bundle.js
import webpack from 'webpack';
import webpackConfig from './webpack.config.js'; // <-- Contains ES6+
const bundler = webpack(webpackConfig);
bundler.run(...);
And execute it with babel:
$ babel-node tools/bundle
P.S.: Calling webpack via JavaScript API might be a better approach (than by calling it via a command line) when you need to implement more complex build steps. E.g. after server-side bundle is ready, startup Node.js app server, and right after Node.js server is started, launch BrowserSync dev server.
See also:
React Starter Kit (package.json/scripts, tools/bundle.js, tools/webpack.config.js)
React Static Boilerplate (run.js, webpack.config.js, node run)
You might not need Gulp.js
Another approach is to have a npm script like this: "webpack": "babel-node ./node_modules/webpack/bin/webpack", and run it like so: npm run webpack.
This is what worked for me using webpack 4:
In package.json:
"scripts": {
"dev": "cross-env APP_ENV=dev webpack-serve --require #babel/register"
},
"devDependencies": {
"#babel/core": "^7.0.0-rc.1",
"#babel/register": "^7.0.0-rc.1",
"#babel/preset-env": "^7.0.0-rc.1",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2"
},
"babel": {
"presets": [
["#babel/preset-env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"transform-es2015-modules-commonjs"
]
}
You can clearly see how each dependency is used, so no surprises there.
Note I am using webpack-serve--require, but if you want to use the webpack command instead, replace it with webpack --config-register. In either case, #babel/register is needed to make this work.
And that's it!
yarn dev
And you are able to use es6 in the config!
For webpack-dev-server, use the --config-register option which is the same as with the webpack command
NOTE:
NO need to rename the config file to webpack.config.babel.js (as suggested by the accepted answer). webpack.config.js will work just fine.
I had a problem getting #Juho's solution running with Webpack 2. The Webpack migration docs suggest you to turn of babel module parsing:
It is important to note that you will want to tell Babel to not parse
these module symbols so webpack can use them. You can do this by
setting the following in your .babelrc or babel-loader options.
.babelrc:
{
"presets": [
["es2015", { "modules": false }]
]
}
Sadly, this conflicts with the automatic babel register functionality. Removing
{ "modules": false }
from the babel config got things running again. However, this would result in breaking tree-shaking, so a complete solution would involve overwriting the presets in the loader options:
module: {
rules: [
{
test: /\.js$/,
include: path.resolve('src'),
loader: 'babel-loader',
options: {
babelrc: false,
presets: [['env', {modules: false}]]
}
}
]
}
Edit, 13th Nov 2017; updated webpack config snippet to Webpack 3 (thanks to #x-yuri). Old, Webpack 2 snippet:
{
test: /\.js$/,
exclude: ['node_modules'],
loader: 'babel',
query: {
babelrc: false,
presets: [
['es2015', { modules: false }],
],
},
},
This is really easy, but it wasn't obvious to me from any of the answers, so if anyone else is confused like me:
Just append .babel to the part of your filename before the extension (assuming that you have babel-register installed as a dependency).
Example:
mv webpack.config.js webpack.config.babel.js
Configuration for Babel 7 & Webpack 4
package.json
...
"scripts": {
"start": "webpack-dev-server --env.dev",
"build": "webpack --env.prod",
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.0.0",
"#babel/plugin-proposal-class-properties": "^7.0.0",
"#babel/preset-env": "^7.0.0",
"#babel/preset-react": "^7.0.0",
"#babel/register": "^7.0.0",
"babel-loader": "^8.0.0",
...
"webpack": "^4.17.2",
"webpack-cli": "^3.1.0",
"webpack-config-utils": "^2.3.1",
"webpack-dev-server": "^3.1.8"
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
webpack.config.babel.js
import webpack from 'webpack';
import { resolve } from 'path';
import { getIfUtils, removeEmpty } from 'webpack-config-utils';
export default env => {
const { ifProd, ifNotProd } = getIfUtils(env);
return {
mode: ifProd('production', 'development'),
devtool: ifNotProd('cheap-module-source-map'),
output: {
path: resolve(__dirname, ifProd('prod', 'dev')),
filename: 'bundle.js'
},
For TypeScript: straight from https://webpack.js.org/configuration/configuration-languages/
npm install --save-dev typescript ts-node #types/node #types/webpack
# and, if using webpack-dev-server
npm install --save-dev #types/webpack-dev-server
then proceed to write your, e.g.:
webpack.config.ts
import path from 'path';
import webpack from 'webpack';
const config: webpack.Configuration = {
mode: 'production',
entry: './foo.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'foo.bundle.js'
}
};
export default config;
Check the link for more details where you can use a plugin to have a separate tsconfig file just for the webpack config if you're not targeting commonjs (which is a req for this to work since it relies on ts-node).
For readers in 2022:
"webpack": "^5.70.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
Add "type": "module" in package.json
Change the syntax of your webpack.config.js to ESM.
Enjoy.
One more way is to use require argument for node:
node -r babel-register ./node_modules/webpack/bin/webpack
Found this way in electron-react-boilerplate, look at build-main and build-renderer scripts.
Rename webpack.config.js to webpack.config.babel.js.
Then in .babelrc: {"presets": ["es2015"]}
However, if you want to use a different babel config for babel-cli, your .babelrc might look something like this:
{
"env": {
"babel-cli": {
"presets": [["es2015", {"modules": false}]]
},
"production": {
"presets": ["es2015"]
},
"development": {
"presets": ["es2015"]
}
}
}
And in package.json:
{
"scripts": {
"babel": "BABEL_ENV='babel-cli' babel src -d dist/babel --source-maps",
"build-dev": "NODE_ENV='development' webpack -d --progress --profile --colors",
...
},
...
}
It's dumb but the {"modules": false} will break webpack if you don't use different envs.
For more info about .babelrc, check the official docs.
Don't have enough rep to comment, but I wanted to add for any TypeScript users out there a similar solution to #Sandrik above
I have two scripts that I use pointing to webpack configs (JS files) that contain ES6 syntax.
"start-dev": "./node_modules/.bin/ts-node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --config ./webpack/webpack.config.dev.js"
and
"build": "./node_modules/.bin/ts-node ./node_modules/webpack/bin/webpack.js --config webpack/webpack.config.js"
Using Webpack 4 and Babel 7
To setup a webpack configuration file to use ES2015 requires Babel:
Install dev dependencies:
npm i -D webpack \
webpack-cli \
webpack-dev-server \
#babel/core \
#babel/register \
#babel/preset-env
npm i -D html-webpack-plugin
Create a .babelrc file:
{
"presets": ["#babel/preset-env"]
}
Create your webpack config, webpack.config.babel.js:
import { resolve as _resolve } from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const config = {
mode: 'development',
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'src/index.html'
})
],
resolve: {
modules: [_resolve(__dirname, './src'), 'node_modules']
}
};
export default config;
Create your scripts in package.json:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack-dev-server --open"
},
Run npm run build and npm start.
The webpack config is based on a sample project with the following directory structure:
├── README.md
├── package-lock.json
├── package.json
├── src
│ ├── Greeter.js
│ ├── index.html
│ └── index.js
└── webpack.config.babel.js
Sample project: Webpack Configuration Language Using Babel
My Best approach along with npm script is
node -r babel-register ./node_modules/webpack/bin/webpack
and configure rest of scripts as per your requirement for Babel
After tons of the documents...
Just install es2015 preset (not env !!!) and add it to
.babelrc:
{
"presets": [
["es2015", { "modules": false }]
]
}
Rename your webpack.config.js to webpack.config.babel.js
Adding es6 to webpack is a 3 step process
In webpack.config.js add
module:{
rules:[
{
test: /\.js$/,
loader: 'babel-loader'
}
]
}
Create a .babel.rc and add inside it
{
"presets": ["#babel/env", "#babel/react"],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
]
]
}
in package.json add
npm install #babel/core --save-dev
npm install #babel/preset-env --save-dev
npm install #babel/preset-react --save-dev
npm install #babel/plugin-proposal-class-properties --save-dev
npm install babel-loader --save-dev
Edit: Works as of Feb 2021
https://github.com/webpack/webpack-cli/pull/2381
You can't. You have to convert it to CommonJS, either with babel or esm.
https://github.com/webpack/webpack-cli/issues/282
But you can run webpack -r esm #babel/register
We have installed karma, which is using mocha and chai for tests. We are trying to integrate babel straight into karma using karma-babel-preprocessor, to do the converting of our ES6 files into ES5 to be run. Using mocha individually works with babel, i.e. a mocha test command, but we try to use karma instead it doesn't work.
karma.conf.js snippet:
frameworks: ['mocha', 'chai'],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src/**/*.js': ['babel'],
'test/**/*_spec.js': ['babel']
},
"babelPreprocessor": {
options: {
presets: ['es2015'],
sourceMap: 'inline'
},
filename: function(file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function(file) {
return file.originalPath;
}
},
// list of files / patterns to load in the browser
files: [
'src/**/*.js',
'test/**/*_spec.js'
],
package.json snippets:
"scripts": {
"test": "./node_modules/karma/bin/karma start karma.conf.js"
},
"babel": {
"presets": ["es2015"]
},
"devDependencies": {
"babel-preset-es2015": "^6.1.18",
"chai": "^3.4.1",
"karma": "^0.13.15",
"karma-babel-preprocessor": "^6.0.1",
"karma-chai": "^0.1.0",
"karma-mocha": "^0.2.1",
"karma-phantomjs-launcher": "^0.2.1",
"phantomjs": "^1.9.18",
"redux": "^3.0.4"
}
We get the following error:
PhantomJS 1.9.8 (Mac OS X 0.0.0) ERROR
ReferenceError: Can't find variable: exports
at Users/alexgurr/BT/FutureVoice/trunk/Portal/server/src/login.es5.js:3
When we evaluate the JS files being loaded, they haven't been converted to ES5, hence the syntax 'export' is still present.
We don't want to use any other frameworks for conversion, ie. webpack, browserify etc.
Thanks!
I've been struggling for the past few hours with the same issue. I'm not sure if your use case is the same as mine, but I finally figured it out.
Code under test src/foo.js:
var foo = "foo value";
export default foo;
Test code tests/foo.spec.js:
import foo from "../src/foo.js";
describe('Foo', function() {
it('should be "foo value"', function() {
expect(foo).toBe('foo value');
});
});
karma.conf.js file before:
{
// other configs
files: [
'src/**/*.js',
'tests/**/*.spec.js',
],
preprocessors: {
'src/**/*.js': ['babel'],
'tests/**/*.spec.js': ['babel'],
},
babelPreprocessor: {
options: {
"presets": ["es2015"]
}
}
}
This yielded the ReferenceError: Can't find variable: exports error you saw.
The fix:
npm install --save-dev babel-plugin-transform-es2015-modules-umd
Add following to karma.conf.js
babelPreprocessor: {
options: {
"presets": ["es2015"],
"plugins": ["transform-es2015-modules-umd"]
}
}
Then the error went away.
Also, note that the following export declarations (which I believe should be correct) do not work.
// exports an object
export default var foo = "something";
// exports undefined
export var bar = "something else";
The problem is that you still didn't bundle/wrap your files to be able to execute CommonJS modules in the browser (because Babel transpile es2015 modules into CommonJS and CJS is default module system for node, not for browsers where Karma run its tests). So your options are:
Use karma-commonjs wrapper (if you want to add all your dependencies manualy)
Use browserify bundler with babelify plugin
Use webpack bundler
I think you still need babel, not just the preset.
npm i babel --save-dev
I have almost the same configuration on one of my project, meaning letting karma pre-process my file on the fly, and the only difference for me is that I have installed babeljs also.
Hope this helps.
Cheers