Webpack cannot identify my JSX syntax inside my js file - reactjs

When i try to bundle my modules with webpack, it cannot identify the JSX syntax inside my index.js file and gives the following error:
ERROR in ./src/index.js 29:3
Module parse failed: Unexpected token (29:3)
You may need an appropriate loader to handle this file type.
| const searchTerm = _.debounce(term => {this.searchTerm(term)}, 300);
| return (
> <div>
| <SearchBar onInputChange= {searchTerm}/>
| <div className="row">
# multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js main[1]
This is my webpack config:
const Path = require('path');
module.exports = {
entry: ['./src/index.js'],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: Path.resolve(__dirname, '../src'),
use: {
loader: 'babel-loader',
options: {
presets: ["#babel/preset-react", "#babel/preset-env"]
}
}
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [ 'css-loader' ]
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './',
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
}
};
I have added the babel presets for react namely #babel/preset-react. I have also added the babel-loader but still it cannot identify the JSX syntax.

I cloned your repo and found a bunch of conflicts on your code setup.
Some of your packages are not aligned with the latest versions of your #babel/core package. If you are going to use the latest version of babel, might as well use the latest presets.
`
devDependencies: {
#babel/cli: ^7.0.0,
#babel/core: ^7.0.0,
#babel/preset-env: ^7.0.0,
#babel/preset-react: ^7.0.0,
babel-loader: ^8.0.0"
}
`
and I removed babel-preset-env and babel-preset-react (the old versions) on your dependencies.
Pick one babel configuration. It's either on your package.json or on .babelrc. I suggest you stick with the .babelrc file. And changed the values of the presets property.
`"presets": ["#babel/preset-react", "#babel/preset-env"],`
On your webpack.config.js you don't need to do include: include: Path.resolve(__dirname, './src'). You can also remove this line:
`presets: ["react", "env"]`
and BTW, on your package.json,
"scripts": {
- "start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
+ "start": "webpack-dev-server --mode development",
...
when you run npm start your project will look into a locally installed webpack-dev-server and use the global one if it does not find the local package.
Hope this helps. :)

Related

Webpack Module parse failed with bootstrap css

I'm trying to build with webpack
npm run build
But I get the following error
ERROR in ./node_modules/bootstrap/dist/css/bootstrap.min.css 1:0
Module parse failed: Unexpected character '#' (1:0)
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
#charset "UTF-8";/*!
| * Bootstrap v5.0.2 (https://getbootstrap.com/)
| * Copyright 2011-2021 The Bootstrap Authors
My webpack config looks like this
const path = require("path");
module.exports = {
mode: "production",
entry: "./paginate.js",
output: {
path: path.resolve("./"),
filename: "index.js",
libraryTarget: "commonjs2",
},
module: {
rules: [
{
test: /\.js|jsx?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
}
}
],
},
externals: {
react: "react",
},
};
.babelrc file looks like
{
"presets": ["#babel/preset-env", ["#babel/preset-react", {
"runtime": "automatic"
}]]
}
I've searched but can't seem to find the right loader for this.
I'm not sure, just a guess, most likely bootstrap is trying to import CSS or scss and you don't have a loader for it defined.
Try adding:
{
test: /\.s?[ac]ss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
exclude: [/node_modules/],
},
To your webpack rules and also install those modules with --save-dev.
Side node, this regular exression test: /\.js|jsx?$/, is incorrect, just use test: /\.jsx?$/,. The "?" means the x is optional.

How can I resolve this issue about Storybook and Sass?

I have an issue about Storybook. I can't start storybook and I have an error about my SCSS file.
Here is the error:
ModuleParseError: Module parse failed: Unexpected token (1:0)
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
.h1 {
| color: red;
| }
at handleParseError (/myproject/node_modules/#storybook/builder-webpack4/node_modules/webpack/lib/NormalModule.js:469:19)
I mean this is juste a simple class. But when the file is empty, the compilation is okay, so I don't understand how I can resolve this.
My SCSS file
.h1 {
color: red;
}
My Webpack file
const webpack = require('webpack');
const path = require('path');
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, './src/index.js'),
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.scss?$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
},
},
],
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js',
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
contentBase: path.resolve(__dirname, './dist'),
hot: true,
},
};
My main.js file in the .storybook folder
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)",
"../src/**/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials"
]
}
Is anyone has a solution please?
Thanks by advance
Finally, I have solved my problem, so here is how I did it.
First of all, I uninstalled the storybook (How to remove storybook from the react project), then the reinstalled via webpack (https://storybook.js.org/blog/storybook-for-webpack-5/).
For once with Webpack it works whereas installing it with NPM (or Yarn for my part) brought me to the complications that I had posted above. My guess is that it works for Webpack 5, whereas with NPM, I was getting an error about the css-loader loader that told me about Webpack 4.
Storybook worked, but I was still worried about .scss files. My terminal told me that I did not have a specific loader. So I took a loader for this type of file by adding a webpack.config.js in the .storybook folder created when we install Storybook. I used the instructions found here: https://storybook.js.org/docs/react/configure/webpack
About Sass files: Storybook is case sensitive, and also doesn't take into account files starting with _, so not possible to use partials
I hope you don't have this kind of problem, but if you do, maybe these answers will help you ^^

Webpack: Can I get a source map for after babel, before minification?

I have a fairly basic webpack setup that runs babel and out comes my minified js with a source map.
Now when I run my source map in chrome I get the js before babel and before minification. However I would often like to have my source map after babel but before minification. Is this possible?
TL;DR I want source map to post-babel pre-minifcation. Possible?
For completeness
I run babel-loader 8 with webpack 4
Here is a screenshot from chrome showing the problem. As you can see the Dropzone tag indicates this is jsx (and so before babel)
Secondly here is my webpack config (not that it actually matters for my question).
const path = require('path');
module.exports = {
context: path.join(__dirname, 'Scripts', 'react'),
entry: {
client: './client'
},
output: {
path: path.join(__dirname, 'Scripts', 'app'),
filename: '[name].bundle.min.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
plugins: [require('#babel/plugin-proposal-object-rest-spread')],
presets: ["#babel/es2015", "#babel/react", "#babel/stage-0"]
}
}
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
externals: {
// Use external version of React (from CDN for client-side, or
// bundled with ReactJS.NET for server-side)
react: 'React'
},
devtool: 'source-map'
};
Running webpack with -d gives a second set of source maps in chrome that does the trick.

Babel convert path jsx to js

I am using babel to transpile some es2015 code to es5, like this:
"scripts": {
"build:lib": "babel src --out-dir lib --presets=react,es2015,stage-0",
"clean": "rimraf lib dist coverage",
"prepublish": "npm run clean && npm run build:lib"
}
It is converting it fine to es5. The problem is that babel is not changing the path among files. It changes the extension of the file from .jsx to .js, but inside the file, it is still referencing the file as .jsx.
To simplify it, the folder structure looks like this. Babel has changed the extensions of the .jsx files:
- index.js
- Component.js
While inside index.js, it is doing keeping the .jsx extension:
require('./Component.jsx');
Am I missing something? Is there a better way to do this?
Thanks for you help:)
Why won't you simply use Webpack for that? Is there a reason for that? especially that you are also missing setting up node_env production so it will avoid adding propTyping etc.
es3ify is just for changing the code, while you are trying to build a library out of it. you need a tree builder like Webpack for something like that (how es3ify would know about the references between each other?)
So tl;dr there is a better solution for that: use Webpack.
module.exports = {
devtool: 'source-map',
entry: [
path.join(__dirname, '/src/index.jsx')
],
output: {
path: path.join(__dirname, '/dist'),
filename: 'bundle.js',
publicPath: '/'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV)
}
}),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
]
};
As Shiroo suggested, I ended up using webpack for this. The key concept here was understanding what resolvers do. They are really well explained in the webpack docs: https://webpack.github.io/docs/resolving.html
resolve: {
root: path.resolve('./src'),
extensions: ['', '.js', '.jsx']
}
Later, I encountered that all the node_modules were also included in the bundle, despite having it explicitly inside the loader:
module: {
loaders: [
{
test: /(\.jsx|\.js)$/,
include: path.resolve('./src'),
exclude: /node_modules/,
loader: 'babel'
}
]
}
This issue is better explained here https://stackoverflow.com/a/35820388/4929834

Using Webpack for hot-loader and generating a physical file w/ ReactJs ES6

I have a ReactJs ES6 (ie 'import' keywords) app that uses gulp for generating a physical build file and webpack for hot-loading the changes to a virtual file. I wanted to combine the two services with npm start (which current loads webpack, not gulp).
server.js file
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(3000, 'localhost', function (err, result) {
if (err) {
console.log(err);
}
console.log('Listening at localhost:3000');
});
webpack.config.js file
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index.js'
],
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'build'),
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel-loader'],
include: path.join(__dirname, 'src'),
exclude: /node_modules/
},
{ test: /\.css$/, loader: 'style-loader!css-loader' }
]
}
};
I thought based on webpack's output section, webpack would generate a physical file in my build folder while creating a virtual file in '/static/bundle.js'
Currently, the virtual file with hot-loader is working, but no physical file has been built in the 'build' path.
Am I correct that webpack can replace gulp and generate both a physical & virtual build file? If so, where is my code in err as far as creating a physical build file?
Thanks in Advance.
Solution:
My code is fine, I needed to add to my scripts in package.json:
.....
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"gulp": "gulp",
"all": "npm run build && npm run gulp"
.....
I then run "npm run all" and I can run webpack and gulp from one command

Resources