Babel + Webpack doesn't transpile ES6 [duplicate] - reactjs

This question already has answers here:
How to use arrow functions (public class fields) as class methods?
(4 answers)
Closed 5 years ago.
I just set up the environment for a webapp using react.
setInitialStates = () => {
this.state = {showAuthorModal: false};
};
NOTE: This is the correct syntax!
This happens when I tried to run webpack --config webpack.config.js
This is my webpack.config.js.
const path = require('path');
module.exports = {
entry: {
component: [
'./public/javascripts/Rendering.jsx',
'./public/javascripts/CentreQuote.jsx',
'./public/javascripts/AuthorModal.jsx',
'./public/javascripts/LeftNav.jsx'
]
},
output: {
path: path.resolve('public/javascripts'),
filename: 'index_bundle.js'
},
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }
]
}
}
Then I have .babelrc,
{
"presets":[
"es2015", "react"
],
"plugins": ["transform-es2015-arrow-functions"]
}
I think I'm missing some wiring step that links babelrc to the loader config?

replace the "module" in webpack with the following:
module: {
rules: [{
test: /\.jsx?$/,
loader: "babel-loader",
options: {
cacheDirectory: true, //false for production
babelrc: false,
presets: ["es2015", "react"],
plugins: ["transform-es2015-arrow-functions"]
}
}]
}
I did 2 things:
unified the js/jsx loader in one regex test
stopped using the babelrc to be able to specify the configs inside webpack.
it should work! give it a try
The main issue with the code you provided is that you have "loaders" but it should be "rules"

Related

React/TypeScript unexpected token

I'm building out a react/TS app and am running into this compiler error. I'm sure it's a config issue, but alas, I can't figure out which config. I'm not sure if it has to do with the generic specifically, or if I will see the "unexpected token" error show up in other circumstances as well.
ERROR in ./src/App.tsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/.../src/App.tsx: Unexpected token (15:4)
13 | const [coordinates, setCoordinates] = useState<
14 | CoordinatesQueryType | undefined
> 15 | >();
| ^
16 |
Webpack config follows. FWIW I added "react" to module.rule.options, but then i got another error that said I was missing "babel-preset-react", installed that, then another error, and then didn't wanna go down the rabbit hole.
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.tsx",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["#babel/env"] }
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
resolve: { extensions: ["*", ".js", ".jsx", ".ts", ".tsx"] },
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js"
},
devServer: {
port: 4000,
hot: true
},
plugins: [new webpack.HotModuleReplacementPlugin()]
};
And babel.rc:
{
"presets": ["#babel/env", "#babel/preset-react", "#babel/preset-flow"],
"plugins": ["#babel/plugin-transform-runtime"]
}
Is there any setup for typescript?
I think you are missing this in babel presets:
#babel/preset-typescript
And also I can't see any ts-loader in your webpack config. So you would not get typechecking even though you compile typescript. To fix this:
Change current rule for babel to match only js files
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["#babel/env"] }
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
Install necessary tools:
yarn add -D #babel/preset-typescript ts-loader
Add #babel/preset-typescript to babel.rc presets.
Add ts-loader to webpack.config.js module rules.
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["#babel/env"] }
},
// Typescript loader
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: ["ts-loader"],
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
I think this should be able to fix the problem.
Also, you are having both options\presets and .babelrc, try to use only one of these for configuration.

Prefix React className

So, I need to prefix my react components classNames so it doesn't conflict with global classes.
And no, I can't use CSS modules because of how my yarn workspaces are built
So, if I have a button class I would like it to become my_app-button
<button className="button">Hello StackOverflow</button>
to
<button className="my-app_button">Hello StackOverflow</button>
PostCSS does that for me in the CSS part, but on the React Side I wasn't able to find a solution
All of my components use typescript
I've tried using a webpack loader to do the job, and it did! But only on my Storybook server, when I used it with my separate webpack config it didn't work
The only error that is given to me is invariant 85
This is my Webpack Config, alongside the webpack loader and the babel-loader
import { Configuration, ProgressPlugin } from 'webpack'
const config: Configuration = {
mode: 'production',
entry: './src/index.ts',
target: 'node',
output: {
filename: '[name].js',
path: __dirname + '/dist',
publicPath: '',
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['#babel/preset-react', '#babel/preset-env', 'minify'],
},
},
],
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-react',
'#babel/preset-env',
'#babel/preset-typescript',
'minify',
],
},
},
],
},
{
test: /\.tsx$/,
exclude: /node_modules/,
use: [
{
loader: 'react-classname-prefix-loader?prefix=giffy_css',
},
],
},
{
test: /\.(png|jpe?g|gif)$/,
exclude: /node_modules/,
use: [{ loader: 'file-loader' }],
},
],
},
plugins: [new ProgressPlugin()],
}
export default config
and just in case you need it, this is my Storybook webpack configuration
webpackFinal: async (config, { configType }) => {
config.module.rules.push({
test: /\.tsx$/,
exclude: /node_modules/,
use: [
{
loader: 'react-classname-prefix-loader?prefix=giffy_css',
},
],
})
// console.log(config.module.rules[0].use[0].options.overrides[0])
return config
}
i have also tried first compiling my components with babel and then using webpack
i tried searching for an equivalent webpack loader in babel, but could not find it

`require is not defined` error when using electron with a react app

I have a React-based web application and I'm trying to build an electron app out of it. I have gotten quite far and the app seems to load but somewhere in between I get an error saying require is not defined.
These are the versions of the tools I'm using:
webpack 3.6
react 15.6.1
electron 1.7.6
Here's a screenshot of the line where the error occurs:
Note that require is defined in Console - I read somewhere that this could be a race condition, but even if that's the case, what do I do about it?
Here's my webpack.config.js (note that I'm using the electron-renderer target):
var path = require('path');
var webpack = require('webpack');
var StatsPlugin = require('stats-webpack-plugin');
var devServerPort = 3808;
var presets = ['es2015', 'react', 'stage-0'];
var options = {
entry: {
'application': [
'react-hot-loader/patch',
'app/application.jsx'
]
},
output: {path: __dirname, filename: 'js/bundle.js' },
resolve: {
modules: [
path.join(__dirname, 'node_modules/'),
path.join(__dirname, 'app/')
],
extensions: ['.js', '.jsx']
},
node: {
__dirname: false,
__filename: false
},
plugins: [
// must match electron.webpack.manifest_filename
new StatsPlugin('manifest.json', {
// We only need assetsByChunkName
chunkModules: false,
source: false,
chunks: false,
modules: false,
assets: true
}),
new webpack.ProvidePlugin({
"React": "react",
}),
new webpack.ProvidePlugin({
"ReactDOM": "react-dom",
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
'process.env.BASE_URL': JSON.stringify('localhost:3000'),
'global': {}, // bizarre lodash(?) webpack workaround
'global.GENTLY': false // superagent client fix
})
],
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loaders: "babel-loader", query: { presets: ['react', 'es2015', 'stage-0'] }},
{ test: /\.jsx$/, exclude: /node_modules/, loaders: "babel-loader", query: { presets: presets }},
{ test: /\.css$/, loader: "style-loader!css-loader" },
{ test: /\.png$/, loader: "url-loader?limit=100000" },
{ test: /\.jpg$/, loader: "file-loader" },
{ test: /\.(png|)$/, loader: 'url-loader?limit=100000' },
{
test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader"
},
{ test: /\.scss$/, loaders: ["style-loader", "css-loader?sourceMap", "sass-loader?sourceMap"] },
{
test: /\.json$/,
loaders: ['json-loader']
}
]
},
};
options.target = 'electron-renderer';
module.exports = options;
I even tried using webpack-target-electron-renderer but it caused more problems.
I've had a similar issue in the past, if it is in fact the same problem here's how to solve it.
The require you have shown is within the wrapping IIFE, which means that this is not window but the function, meaning that when you try to find require it's not in scope. In order to fix this you need use imports-loader.
In your case, under module and then loaders, add:
{
test: require.resolve("/*require/import path which requires the file where require("url") is*/"),
use: "imports-loader?this=>window"
}
Hope this solves your problem.
You need to use something like browserify or babelify.
See a more in-depth explanation here.

Webpack 2 - Cannot create property 'mappings' on string

Migrating from a working Webpack v1 config to Webpack 2. But running into an error while trying to run the build:
ERROR in ./src/index.jsx
Module build failed: TypeError: /home/pierce/Projects/my-js-app/src/index.jsx: Cannot create property 'mappings' on string
I have updated my loaders to match the new format:
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.(jpg|png)$/,
loader: 'file-loader',
query: {
name: '[path][name].[hash].[ext]',
},
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
options: { sourceMap: true }
}
]
},
{
test: /\.(woff|woff2|eot|ttf|svg)(\?v=\d+\.\d+\.\d+)?/,
loader: 'url-loader',
query: {
limit: 100000
}
},
{
test: /\.icon-svg$/,
use: [{loader:'babel-loader'}, {loader: 'svg-react-loader'}]
},
// Bootstrap 3
{
test: /bootstrap-sass\/assets\/javascripts\//,
loader: 'imports-loader?jQuery=jquery'
}
]
},
It's as if something is not being compiled the way it was before, therefore causing a TypeError.
Turns out I was babelifing twice.
If you're also splitting your webpack.config.js into separate files for your different environments, be sure that webpack.dev.config.js does not include a babel-loader entry if your webpack.base.config.js does.
Otherwise, if you use the loader twice the 2nd time around will cause an error. This wasn't a Webpack 2 error but a webpack splitting-configs-and-missing-a-small-thing error
Encountered a similar issue in my compilation. Found out that I was using babel loader for .js and .jsx both.
Removed .jsx and its working as expected.
A snippet of my webpack.config.js looks like this.
{
test: /\.js$/,
exclude: [/(node_modules)/],
use: [
{
loader: 'react-hot-loader'
},
{
loader: 'babel-loader',
options: {
presets: ['react', 'es2015', 'stage-0'],
plugins: [
'transform-class-properties',
'transform-decorators-legacy'
]
}
}
]
}
In case someone else is having the same issue, I had to remove the following from loader for it to work
{
test: /\.jsx?$/,
use: ['react-hot-loader/webpack']
}
In my case it helped when I removed devtool: 'inline-source-map' from webpack

Webpack, React, Babel - Cannot Resolve module

I have installed react-hot-loader and referenced the module in the webpack.config.js. However when i try to run webpack to compile the scripts, i get an error.
Please see below screen shot. Could someone please advise of what the issue could be. FYI, i am using all the latest libraries.
[1]: http://i.stack.imgur.com/2GCa1.jpg
/*webpack.config.js
module.exports = {
devtool: 'eval-source-map',
entry: {
main: [
'./src/main.js'
]
},
output: {
filename: './public/[name].js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: ['react-hot','babel-loader'],
query: {
presets: ['es2015', 'react']
}
}
]
}
}
/*UPDATE*/
Code update
I have added an "s" after loader. It is now giving me the below error.
[2]: http://i.stack.imgur.com/LL1nn.jpg
Based on your second picture, you could try the following:
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: ['react-hot'],
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: ['babel-loader'],
query: {
presets: ['es2015', 'react']
}
}
]
I've created a starter with webpack, babel and react-hot-loader. Please have a look into my config: https://github.com/skrobek/webpack-react/blob/master/webpack.config.js
and package.json https://github.com/skrobek/webpack-react/blob/master/package.json#L19
Feel free to use it :-)

Resources