webpack babel loader fails to compile jsx - javascript

I'm trying to run a simple boilerplate for react + webpack + hot module replacement. But I'm actually stuck on babel/jsx step and need help. I'm following this article.
Currently I've got:
webpack.config.js:
module.exports = {
context: __dirname + "/app",
entry: "./app.js",
output: {
filename: "app.js",
path: __dirname + "/dist",
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ["babel-loader"],
}
],
},
}
app/app.js:
import React from "react";
import Greeting from "./greeting";
React.render(
<Greeting name="World"/>,
document.body
);
and app/greetings.js:
import React from "react";
export default React.createClass({
render: function() {
return (
<div className="greeting">
Hello, {this.props.name}!
</div>
);
},
});
and this in package.json:
"devDependencies": {
"babel-core": "^6.18.0",
"babel-loader": "^6.2.7",
"webpack": "^1.13.3"
},
"dependencies": {
"react": "^15.3.2"
}
When I run just webpack in the console, as the tutorial says, it should run webpack (and babel underneath) and bundle the whole app, but it doesn't - instead, it throws following error:
$ webpack
Hash: 9a56cc72acac2de6f40c
Version: webpack 1.13.3
Time: 543ms
+ 1 hidden modules
ERROR in ./app.js
Module build failed: SyntaxError: C:/Users/abc/Tests/webpack-react-hmr/app/app.js: Unexpected token (7:2)
5 |
6 | React.render(
> 7 | <Greeting name="World"/>,
| ^
8 | document.body
9 | );
10 |
I'm new to this topic, so I don't know what the problem is, but surely, webpack can't understand JSX syntax. Maybe this part of the tutorial is either wrong or out of date:
Fortunately the Babel loader supports transforming both ES2015 and JSX which
means we can get away with using a single loader instead of requiring
both the babel-loader and the jsx-loader.
We can install the babel loader with the following command:
npm install babel-loader --save-dev
What should I do in order to fix the webpack/jsx/babel setup?

You need babel presets to compile react and other ES6, ES7 features.
The list of required presets:
latest
react
stage-0
Add this file as .babelrc to your root.
{
"presets": ["latest", "react", "stage-0"],
}
and do this installation
npm install --save-dev babel-preset-latest babel-preset-react babel-preset-stage-0
Now, run webpack. It should work!

You need to install the babel. That's the key for compiling the jsx files.
First install it:
npm i -D #babel/preset-react #babel/preset-env #babel/core babel-loader #babel/plugin-proposal-class-properties
And then create the following files, and set the configurations like the following
/
.babelrc
webpack.config.js
.babelrc file:
{
"presets": [
[ "#babel/preset-env", {
"modules": false,
"targets": {
"browsers": [
"last 2 Chrome versions",
"last 2 Firefox versions",
"last 2 Safari versions",
"last 2 iOS versions",
"last 1 Android version",
"last 1 ChromeAndroid version",
"ie 11"
]
}
} ],
"#babel/preset-react"
],
"plugins": [ "#babel/plugin-proposal-class-properties" ]
}
webpack.config.js file:
module.exports = {
...
module: {
rules: [
{
test: /\.js?$/,
exclude: /node_module/,
use: 'babel-loader'
},
]
}
};
Now run the webpack. It must work fine.

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'));
...

How to resolve 'class constructor cannot be invoked without new' error when building with svelte, babel, and webpack

I'm trying to get svelte, webpack, and babel to work together. I am producing the minified bundle, however, this bundle is throwing errors upon loading it up in the browser. This needs to be compatible with IE11 while using ES6 syntax.
I get
Class constructor I cannot be invoked without 'new'
The pertinent parts of my webpack looks as follows
{
test: /\.(js|jsx|mjs|svelte)?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
configFile: path.resolve(__dirname, 'babel.config.js')
}
}
]
},
{
test: /\.svelte$/,
exclude: /node_modules/,
use: {
loader: "svelte-loader",
options: {
emitCss: false,
hotReload: false
},
},
},
babel.config is as follows
module.exports = {
plugins: [
'#babel/plugin-proposal-class-properties',
'angularjs-annotate',
'lodash'
],
presets: [
['#babel/preset-env', {
useBuiltIns: 'usage',
corejs: { version: 3, proposals: true }
}],
'#babel/preset-react'
]
};
The svelte file itself is pretty basic
<script>
export let name = "World";
</script>
<h1>Hello {name}!</h1>
UPDATE
I can get it to run by excluding transform-classes in babel config
exclude: ['transform-classes'],
However, this of course breaks IE11.
You will need to update the webpack-cli and html-webpack-plugin versions in your package.json:
"webpack-cli": "^4.5.0",
"html-webpack-plugin": "^5.1.0",
Then, delete your node_modules and package-lock.json files and run a new npm install
Simply do this:
$ yarn remove webpack-cli && yarn add --dev webpack-cli
This will remove the old cli version, re-install the new one and compile everything afresh. Problem solved

preset-env and core-js don't seem to use browserslist

Using the official docs I've been trying to setup an optimal build config using: #babel/preset-env and core-js with a .browserslist file.
As far as I understand the docs, they say that preset-env with useBuiltins:"usage" will update the import 'core-js/stable' statement in my code, to only include the required functions.
However, no matter if I set last 1 chrome version or >1% in NL (which are considerably more and older browsers), the build file is the same size (about 3MB).
What am I missing?
I have a test repo available here: https://github.com/publicJorn/jorns-react-starter
For quick reference, the relevant files:
.babelrc
{
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "usage",
"corejs": { "version": 3, "proposals": true }
}
],
"#babel/preset-react"
],
"plugins": [
[
"#babel/plugin-proposal-object-rest-spread",
{
"useBuiltIns": true
}
],
["#babel/plugin-proposal-class-properties"],
["#babel/plugin-syntax-dynamic-import"],
["babel-plugin-styled-components"]
]
}
webpack part
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
.browserslistrc
> 1% in NL
ie 11
not ie < 11
index.js
import 'core-js/stable'
// etc..
If propertie useBuiltIns was usage, core-js will bundle polyfill code what you are using in project.
If useBuiltIns was entry, it will bundle polyfill code by browserslist setting. don't forget import core-js manually.
import 'core-js/stable';
import 'regenerator-runtime/runtime';
Now, usage and entry are both bundle polyfill by browser setting above #babel/core>=7.18

Webpack babel-loader es2015 presets setting is not working

When I build react project with webpack, I got an 'Unexpected token' error
webpack --progress
ERROR in ./src/App.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (13:13)
11 | }
12 |
> 13 | onSearch = (e) => {
| ^
14 | console.log('click');
15 | }
I thought my project doesn't transpile es6 codes to es5 because wrong setting of webpack.config.js, but I can't find what's wrong.
webpack.config.js
module.exports = {
entry: __dirname + "/src/App.js",
output: {
path: __dirname + "/public",
filename: "bundle.js"
},
module: {
rules: [{
test: /\.js?$/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
presets: ['react', 'es2015']
}
}]
}
}
Install babel-preset-stage-2 package and try this:
.babelrc
{
"presets": ["es2015", "react", "stage-2"]
}
webpack.config.js
...
presets: ["es2015", "react", "stage-2"]
...
In the future, we might not use the babel's state presets as this Removing Babel's Stage Presets article said.
However, for now, it worked really well
What's Babel's Stage Presets:
A Babel preset is a shareable list of plugins.
The official Babel Stage presets tracked the TC39 Staging process for
new syntax proposals in JavaScript.
Each preset (ex. stage-3, stage-2, etc.) included all the plugins for
that particular stage and the ones above it. For example, stage-2
included stage-3, and so on.

Webpack babel-loader runtime: Module build failed: TypeError: this.setDynamic is not a function

I'm trying to use the babel-loader with the babel-plugin-transform-runtime.
I've followed the instructions at:
https://github.com/babel/babel-loader#babel-is-injecting-helpers-into-each-file-and-bloating-my-code
The relevant code:
rules: [
// the 'transform-runtime' plugin tells babel to require the runtime
// instead of inlining it.
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: ['#babel/transform-runtime']
}
}
}
]
And I get the following error on build:
Module build failed: Error: Cannot find module '#babel/plugin-transform-runtime'
If I'm changing the plugin name to: plugins: ['transform-runtime'], I get the following error:
Module build failed: TypeError: this.setDynamic is not a function
What is the problem?
After a struggle I've found the right way to do it.
Tl;dr
If you install the new babel loader, you should load the new babel plugins.
Full story
The install in the official docs:
npm install babel-loader#8.0.0-beta.0 #babel/core #babel/preset-env webpack
In the github page, these were the instructions for the runtime plugin:
NOTE: You must run npm install babel-plugin-transform-runtime
--save-dev to include this in your project and babel-runtime itself as a dependency with npm install babel-runtime --save.
Instead, you should use the new version like this:
npm install --save-dev #babel/plugin-transform-runtime
npm install --save #babel/runtime
Then it would work with the configuration in the documentation.
First, as #yccteam pointed one needs to have installed
npm install --save-dev #babel/plugin-transform-runtime
npm install --save #babel/runtime
.babelrc file should have
{
"presets": [
["#babel/preset-env", {
"debug": false,
"modules": false,
"useBuiltIns": false
}],
"#babel/preset-react"
],
"plugins": [
"#babel/syntax-dynamic-import",
"#babel/plugin-transform-runtime",
[ "#babel/plugin-proposal-class-properties", { "loose": true } ],
"#babel/transform-async-to-generator"
],
"env": {
"production": {
"presets": ["react-optimize"]
}
}
}
webpack.js file should look like
module: {
rules: [
{
test: /(\.js[\S]{0,1})$/i,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['#babel/preset-react', '#babel/preset-env'],
plugins: ['#babel/proposal-class-properties']
},
},
...
Your webpack entry looks the same as the example, so I wonder what happens if you use .babelrc.
{
"plugins": ["transform-runtime"]
}
Do you have the env preset installed as well?

Categories

Resources