Webpack babel-loader es2015 presets setting is not working - javascript

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.

Related

Webpack unexpected token react native

I'm trying to integrate a connection to Ledger nano X devices, into a native Swift package. Unfortunately Ledger only provide an SDK as a ReactNative module. I dislike ReactNative and really don't want to integrate it into my entire Swift package, and force it onto my users, just for this one library.
I've had limited success in the past converting NodeModules into plain .js files that I can run directly with iOS's JavascriptContext. I've used webpack to bundle it up into a single plain js file (no require, import, export etc keywords). Adding a native Swift wrapper around that lets me keep all the messy dev setup and tools out of my project and just leverage the plain JS when needed for small use-cases. I've very little experience with this and what i've done in the past isn't working, hours of googling hasn't gotten me any closer.
Building the entire Ledgerjs with webpack was throwing up errors, since I only need pieces of it I started trying to get one of the sub-packages #ledgerhq/react-native-hw-transport-ble to build. I forked the project and added this webpack.config.js
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
"ledger_transport_ble": ['./src/awaitsBleOn.ts', './src/BleTransport.ts', './src/monitorCharacteristic.ts', './src/remapErrors.ts', './src/timer.ts', './src/types.ts']
},
mode: 'production',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.(js|jsx)$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
},
devtool: 'source-map',
resolve: {
extensions: ['.tsx', '.ts', '.js', '.jsx'],
modules: ['node_modules'],
fallback: {
"stream": require.resolve("stream-browserify")
}
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
library: ['[name]'],
libraryTarget: "var"
},
plugins: [
new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'] })
],
};
with this .babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-flow"
]
}
and I get back this error:
ERROR in ./node_modules/react-native-ble-plx/index.js 11:7
Module parse failed: Unexpected token (11:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| export { State, LogLevel, ConnectionPriority, ScanCallbackType, ScanMode } from './src/TypeDefinition'
|
> export type {
| Subscription,
| DeviceId,
# ./src/BleTransport.ts 87:29-60
Instructions online where to add the .babelrc file that I added above, but it made no difference. Have I missed a step somewhere? Or is there something else I should be doing?

Webpack not building ES6 class missing config issue

I am having an issue adding webpack to an existing React project. Previously, the project was rendered server-side with next.js. However, there seems to be something wrong with my webpack config. Whenever I try to build my project, it fails with seemingly valid ES6 code:
ERROR in ./src/components/shared/menu/component.js
Module build failed: SyntaxError: Unexpected token (8:12)
6 |
7 | export default class Menu extends PureComponent {
> 8 | propTypes = {
| ^
9 | items: PropTypes.arrayOf(PropTypes.shape({
10 | name: PropTypes.string.isRequired,
11 | action: PropTypes.func.isRequired,
My webpack.config.js
const path = require('path');
module.exports = {
entry: './src/pages/index/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS
]
}
]
},
devServer: {
contentBase: path.resolve(__dirname, "dist")
}
};
My .babelrc
{ "presets": ["es2015", "react"] }
I've already tried search on SO and google, but cannot find anyone else experiencing the same issue. Please advise! Thanks!
1) run: npm install --save-dev babel-plugin-transform-class-properties
2) Update your .babelrc file:
{ "presets": ["es2015", "react"], "plugins": ["transform-class-properties"] }
That way, babel will also transform class properties as specified in the README: https://www.npmjs.com/package/babel-plugin-transform-class-properties
Also, make sure to use the keyword static when you define propTypes inside a class (so that it will be declared on the class itself, not on its prototype)
Use babel polyfill plugin, and have it included in webpack before your entry points, that means have entry point as array and first elemen is 'babel-polyfill' and second element is your index.js
You could also have require or import babel-polyfill as the first line index.js but only needed to have it once either in webpack or index file.

Node JS Webpack Babel with async

When trying to compile my server-side code, I get the following error:
Module parse failed: (...babel-loader-path)?{"presets":["es2015-node4","es2015"]} (...) Unexpected token (86:6)
You may need an appropriate loader to handle this file type.
This error seems to be caused by an Async function that I am trying to import. Do I need to change my webpack configuration?
My webpack config file:
const webpack = require('webpack');
module.exports = {
target: 'node',
entry: ['./server/index.js', './node_modules/webpack/hot/poll?1000'],
output: {
path: './dist',
filename: 'server.bundle.js',
libraryTarget: 'commonjs',
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
externals: [/^[a-z]/],
module: {
loaders: [{
test: /\.jsx$/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015-node4', 'es2015'],
},
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015-node4', 'es2015'],
},
}
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
devtool: 'source-map',
};
If you are using Webpack to compile your Node code, then that is not a good approach. You should simply use babel-node which is an amazing way to transpile your node code.
For that in your package.json do the following
"scripts": {
"dev": "node_modules/.bin/nodemon --exec babel-node server/index.js",
"prestart": "node_modules/.bin/babel server --out-dir dist",
"start": "node dist/index.js"
},
"devDependencies": {
"#babel/cli": "^7.0.0-beta.40",
"#babel/core": "^7.0.0-beta.40",
"#babel/node": "^7.0.0-beta.40",
"#babel/preset-env": "^7.0.0-beta.40",
"#babel/preset-stage-2": "^7.0.0-beta.40",
"nodemon": "^1.11.0"
}
In your .babelrc file, do the following.
{
"presets": [
"#babel/preset-env",
"#babel/preset-stage-2"
]
}
Then in your project directory create a folder called server and in that folder create a file called index.js which creates your node http server.
For a reference have a look at Babel-Node Documentation
Or have a look at this amazing small tutorial kind of example created by the awesome folks at Babel Example Node Server Using Babel-Node
P.S: In the package.json file the npm run dev watches your code and npm start commands compiles your code ready to be shipped for production.
There seems to be a mis-understanding with regard to the babel preset usage. The preset you want is not the target version of javascript you want to output. For that you need to set target appropriately. Instead you needed the preset that corresponds to the version of javascript you are writing in. The presets are collections of transformers that instruct babel how to deal with specific javascript constructs.
In babel <=6 you need either: es2017 or transform-async-to-generator presets to use the async keyword. After babel 7 the recommendation is to use:
{
"presets": ["#babel/preset-env"]
}
This allows babel to support all modern java-script syntax's that have been finalized. It will then transpile to whatever syntax your target setting indicates. I personally would use a browserslist query in package.json for this so other tools like postcss automatically pick up the same target information.

Webpack's UglifyJsPlugin not able to compile ES6 packages

I have this in my Webpack setup:
// webpack.prod.conf.js
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
drop_console: shouldDropConsole
},
sourceMap: true
}),
// .babelrc
"presets": [
["stage-2"],
["es2015", {"modules": false}]
],
When I do npm run build I get the following error:
ERROR in static/js/vendor.8b608f0ab832a371f4a5.js from UglifyJs
Unexpected token: name (finish)
[./node_modules/pica/lib/mathlib.js:35,0][static/js/vendor.8b608f0ab832a371f4a5.js:38950,6]
So UglifyJS doesn't recognize the ES6 code there: let.
How to solve this? Is there any workaround? (I'm using Webpack 3.6.0).
I found the solution (how to transpile ES6 to ES5 for node modules in a Webpack setup):
{
test: /\.js$/,
loader: 'babel-loader',
include: [
resolve('src'),
resolve('test'),
resolve('node_modules/pica'),
resolve('node_modules/countries-list')
],

webpack babel loader fails to compile jsx

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.

Categories

Resources