Babel 7 - ReferenceError: regeneratorRuntime is not defined - javascript

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

Related

ReferenceError: regeneratorRuntime is not defined working on vanilla js [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'));
...

Vuejs 3 webpack : Problem with vue-template-compiler

I am trying to integrate vuejs 3 to an existing project which uses webpack. I read about vue-loader, so I am trying to use it.
In the official documentation I have this:
Every time a new version of vue is released, a corresponding version of vue-template-compiler is released together. The compiler's version must be in sync with the base vue package so that vue-loader produces code that is compatible with the runtime. This means every time you upgrade vue in your project, you should upgrade vue-template-compiler to match it as well.
So, when I try to compile I get this error:
Vue packages version mismatch:
- vue#3.0.2 (/home/alejo/playground/parquesFrontend/node_modules/vue/index.js)
- vue-template-compiler#2.6.12 (/home/alejo/playground/parquesFrontend/node_modules/vue-template-compiler/package.json)
This may cause things to work incorrectly. Make sure to use the same version for both.
If you are using vue-loader#>=10.0, simply update vue-template-compiler.
If you are using vue-loader#<10.0 or vueify, re-installing vue-loader/vueify should bump vue-template-compiler to the latest.
But when I try to install vue-template-compiler#3.0.2 I get this error:
❯ npm install vue-template-compiler#3.0.2
npm ERR! code ETARGET
npm ERR! notarget No matching version found for vue-template-compiler#3.0.2.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/alejo/.npm/_logs/2020-11-17T02_52_46_458Z-debug.log
How can I solve this problem?
To make vue 3 work fine with webpack without using vite or vue cli follow these steps :
init the package.json like :
{
"private": true,
"name": "vue-3",
"description": null,
}
install the last version of vue :
npm i --save vue#next vue-loader#next
install also the dev dependencies that includes #vue/compiler-sfc which replaces vue-template-compiler
npm i -D #vue/compiler-sfc css-loader file-loader mini-css-extract-plugin
url-loader webpack webpack-cli webpack-dev-server
#vue/compiler-sfc
css-loader
file-loader
mini-css-extract-plugin
url-loader
vue-loader
webpack
webpack-cli
webpack-dev-server
create or edit your webpack.config.js with following content :
const path = require("path");
const { VueLoaderPlugin } = require("vue-loader");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = (env = {}) => ({
mode: env.prod ? "production" : "development",
devtool: env.prod ? "source-map" : "cheap-module-eval-source-map",
entry: [
require.resolve(`webpack-dev-server/client`),
path.resolve(__dirname, "./src/main.js")
].filter(Boolean),
output: {
path: path.resolve(__dirname, "./dist"),
publicPath: "/dist/"
},
resolve: {
alias: {
// this isn't technically needed, since the default `vue` entry for bundlers
// is a simple `export * from '#vue/runtime-dom`. However having this
// extra re-export somehow causes webpack to always invalidate the module
// on the first HMR update and causes the page to reload.
vue: "#vue/runtime-dom"
}
},
module: {
rules: [
{
test: /\.vue$/,
use: "vue-loader"
},
{
test: /\.png$/,
use: {
loader: "url-loader",
options: { limit: 8192 }
}
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: { hmr: !env.prod }
},
"css-loader"
]
}
]
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: "[name].css"
})
],
devServer: {
inline: true,
hot: true,
stats: "minimal",
contentBase: __dirname,
overlay: true,
injectClient: false,
disableHostCheck: true
}
});
Add dev script to run your app :
{
"private": true,
"scripts": {
"dev": "webpack-dev-server"
},
"dependencies": {
"vue": "^3.0.2"
},
"name": "vue-3",
"description": null,
"devDependencies": {
...
}
}
Fill the index.html with following content :
<link rel="stylesheet" href="/dist/main.css" />
<div id="app"></div>
<script src="/dist/main.js"></script>
Finally run npm run dev the visit http://localhost:8080/
for a ready to use project try to clone this REPOSITORY which built by following the steps above.
I believe you need to use vue-loader#next with Vue 3
In Vue 3 the SFC compiler package is no longer vue-template-compiler but compiler-sfc (check here)
I completely agree with the suggestion to use Vue CLI to manage the project - it will save you lot of trouble managing all the dependencies (especially now when Vue 3 ecosystem is trying to catch-up with Vue 3 release and lots of tool even don't have any migration documentation ....like vue-loader)
If you are not able to use CLI because your existing project already have Webpack config, you can still use CLI as a guide. Just generate new project on the side, use vue inspect command to inspect Webpack config it is using and package.json for required dependencies...
I've just installed the Webpacker gem in rails that comes with nice tasks that install Vue.
Nevertheless, it installs Vue 2.x with its loader and template compiler...
To bump everything to Vue 3 aand its dependencies simply run:
yarn add vue#next vue-loader#next #vue/compiler-sfc
Voila! You're using Vue 3 now
I upgraded a Vue2 app to Vue3 manually and I was getting this error when I was running the unit tests after upgrading all of the dependencies.
To get everything working, I also had to fix Jest's config file.
In jest.config.js set the "transform" property to:
{
transform: '^.+\\.vue$': `vue-jest`
}
The dependencies I used to get started were from a new Vue3.0 app I created using the cli. Below are the dependencies that my cli settings got me:
"dependencies": {
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vue-router": "^4.0.0-0",
"vuex": "^4.0.0-0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-plugin-router": "~4.5.0",
"#vue/cli-plugin-unit-jest": "~4.5.0",
"#vue/cli-plugin-vuex": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0",
"#vue/test-utils": "^2.0.0-0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0-0",
"node-sass": "^4.12.0",
"sass-loader": "^8.0.2",
"typescript": "~3.9.3",
"vue-jest": "^5.0.0-0"
}
Note that for my cli settings, the .eslintrc.js also has some minor changes in it for Vue3. In a fresh install the cli makes the "extends" property as below:
extends: [
`plugin:vue/vue3-essential`,
`eslint:recommended`
],

BabelJS and Webpack config for maximum possible compatibility

My website must work with the most basic phone browsers imaginable, because my user base is rural Ethiopian children on very, very basic handsets. (I am using jquery to save handset battery, as most are 'recycled', second/third/fourth-hand and ancient, and I'm being extremely careful about data costs.)
I am trying to set up Babel + Webpack to transpile for the lowest possible supportable target, but I misunderstand the Babel docs, (eg, I started with #babel/preset-env and no targets, as I assumed that not targeting meant maximum compatibility, but this doesn't polyfill), and can't test against my enormous range of target handsets and browsers.
Will the below config produce and bundle Javascript that'll run on the maximum possible range of browsers? Is there any way to make it more compatible?
I have useBuiltins=usage - will the webpack config below detect repeated imports, and tree shake? If not what do I need to change, or would useBuiltins=entry and require('core-js');require('regenerator-runtime/runtime') in my index.js be better?
Using import or require to import bootstrap generates a larger file than the bootstrap distribution, even though I make no reference to it in the JS. How can I get tree-shaking working? Should I not use jquery via npm? EDIT: Tree shaking only happens on PROD builds, and seems to be working with the below configuration.
Can I safely use the latest jquery and rely on the polyfilling, rather than 1.12, which has security issues but I'm using as it works on much more browsers?
Can I remove #babel/cli, as webpack is running babel? (It works, I just want to be sure I'm getting every ounce of polyfill and compatibility, happy to run babel CLI if better.)
Any other missed opportunities/recommendations?
(If relevant, I do not need any chunking - this is a simple app and I am caching indefinitely. I am writing this into a Django static folder, and Django + whitenoise are handling filename fingerprinting and HTTP compression. I will at some point add JS unit tests. I am importing bootstrap JS for polyfills and tree-shaking (although Bootstrap doesn't seem to be shaking), but loading the bootstrap CSS directly from the HTML to avoid cache misses when I update the app.)
packages.json:
{
...
"scripts": {
"start": "webpack-dev-server --open --mode development",
"build": "webpack --mode production",
},
"devDependencies": {
"#babel/cli": "^7.10.1",
"#babel/core": "^7.10.2",
"#babel/plugin-proposal-class-properties": "^7.10.1",
"#babel/preset-env": "^7.10.2",
"axios": "^0.19.2",
"babel-loader": "^8.1.0",
"bootstrap": "^4.4.1",
"jquery": "^1.12.4", // insecure old version but more compatible
"popper.js": "^1.16.1",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"#babel/polyfill": "^7.10.1",
"core-js": "^3.6.5"
}
}
.babelrc:
{
"presets": [
[
"#babel/env",
{
"targets": "cover 100%",
"useBuiltIns": "usage",
"corejs": "3.6.5"
}
]
],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
webpack.config.js:
const path = require('path');
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
output: {
filename: 'app.js',
publicPath: "/static/",
path: path.join(__dirname, '../djangoproj/app/static/app')
},
devServer: {
writeToDisk: true, // Django serves the content
}
};
index.js:
import $ from 'jquery';
import bootstrap from 'bootstrap'
import popper from 'popper.js'
import {Controller} from './controller';
$(document).ready(function() {
const app = new Controller()
})
controller.js:
import {View} from './view';
import {ActivityStore, ElementStore} from './store';
import {Api} from './api';
export class Controller {
constructor() {
this.state = {}
this.api = new Api(config)
// and so on..
Update: I have decided not to progressively polyfill (using <script type="module" ..) as #tfr recommends below, as it is more important to me to test for the lowest phones than optimise newer phones. This is more likely if I'm running the polyfills on my more modern test devices. That said, core-js claims to only polyfill if necessary, so I'm not sure whether nomodules really makes a difference beyond bundle size (so much of my understanding of this technology is choosing which bit of info I trust my understanding of more). I also decided to load Bootstrap and Popper direct from the browser rather than bundled. I am looking into generating a vendor.js but not sure there are any advantages, except perhaps that they'll load before the polyfills in my bundle.
Enormous thanks.
Normally the best way would be to bundle dual (modern browser and legacy) the same time, so you don't have to polyfill modern devices. Take a look at this working polyfill example.
Thats how you could load es6 for modern and es5 bundle for legacy browser:
<!-- main bundle -->
<script type="module" src="/assets/scripts/main.js"></script>
<!-- polyfilled legacy browser -->
<script nomodule src="/assets/scripts/main.legacy.js" defer="defer"></script>
And here the main answer to your question:
Babel Config
============
const legacy = {
presets: [
["#babel/preset-env", {
targets: {
browsers: [
"> 1% in ET", // make sure its the right country code
"ie >= 6",
"not dead"
]
},
useBuiltIns: "usage",
corejs: 3,
}]
],
plugins: [
"#babel/plugin-syntax-dynamic-import",
"transform-eval"
],
comments: false,
cacheDirectory: path.join(CACHE_PATH, 'babel-loader')
};
Webpack Config
==============
const prod = {
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
exclude: [
/node_modules/
],
use: {
loader: 'eslint-loader',
},
},
{
test: /\.js$/,
exclude: [
/node_modules/
],
loader: "babel-loader",
options: babelConfig
}
]
},
resolve: {
extensions: ['.js', '.json'],
}
};
snippets from https://github.com/unic/darvin-webpack-boilerplate/blob/master/webpack/settings/javascript-legacy/index.js

Setting up Webpack with Babel for ES6 coding [duplicate]

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

Babel [karma-babel-preprocessor] Not Converting ES6->ES5 for Karma Tests

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

Categories

Resources