Hetting error in react build with webpack - reactjs

I am using react.js & web pack. when run the NPM run build command get this error I am learning the how to make build with web pack so I try first time but getting this error. please help!
I write this code from some web pack tutorial website.
assets by status 1.05 KiB [cached] 2 assets
./src/index.js 796 bytes [built] [code generated] [1 error]
ERROR in ./src/index.js 13:2
Module parse failed: Unexpected token (13:2)
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
| const ProviderComponent = ()=>{
| return (
> <Provider store={store} >
| <App/>
| </Provider>
webpack 5.65.0 compiled with 1 error in 901 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
Web pack file
const port = process.env.PORT || 8080;
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = {
output :{
path:path.join(__dirname,'/dist'),
filename:'main.[fullhash].js'
},
module:{
rules:[{
test:/\.(js|jsx)$/,
exclude:/node_modules/,
},
{
test: /\.less$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{ loader: 'less-loader' }
]
},
]
},
resolve:
{
mainFiles: ['index', 'Index'],
extensions: ['.js', '.jsx','.css'],
alias: {
'#': path.resolve(__dirname, 'src'),
}
},
plugins:[
new HtmlWebPackPlugin({
template:'./public/index.html'
})
],
devServer:{
host:'localhost',
port:port,
historyApiFallback:true,
open:true
}
}

You have JSX in your index.js which is not standard javascript. Webpack by default can only transpile standard javascript, for transpiling JSX which is a react feature, you need to use something that can help webpack recognize the syntax of JSX, webpack calls this things loaders.
There are different loaders which you can use, here for example you should use babel-loader to tell webpack how to understand JSX.
babel-loader internally uses Babel.js which is a library for transpiling non -standard javascript into standard javascript.
It's better to get familiar with Babel.js and then use it in webpack. But for now, what you need is this:
Install babel (with preset-react) and babel-loader
npm install -D babel-loader #babel/core #babel/preset-env #babel/preset-react
Add babel to your webpack js|jsx files rule
You can set babel options in the webpack config file like I'm doing here, or create a separate file for configuring babel itself. You can read more about it in Babel.js docs.
...
module:{
rules:[{
test:/\.(js|jsx)$/,
exclude:/node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', "#babel/preset-react"]
}
}
},
...

Related

How to use google fonts in manually created React app?

I created React app manually (not create-react-app) one by one such as index.js, App.js, index.css, components folder etc because I am using React app as a separate app in the Django project.
And in order to use google fonts, I followed this answer.
But when I write #import url('https://fonts.googleapis.com/css?family=Josefin+Sans') in the index.css, it is giving me this error.
ERROR in ./src/index.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
> #import url('https://fonts.googleapis.com/css?family=Josefin+Sans');
|
# ./src/index.js 4:0-21
webpack 5.15.0 compiled with 1 error in 999 ms
I think this error is related to webpack.config.js and it seems I need to add some rules in the module section related to css-loader, file-loader, or something else, but I am not sure how to write.
This is just my thought, I have no idea why this is happening.
webpack.config.js
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "./static/frontend"),
filename: "[name].js",
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
optimization: {
minimize: true,
},
plugins: [
new webpack.DefinePlugin({
"process.env" : {
NODE_ENV: JSON.stringify("production"),
}
})
]
};
How to solve this issue? (This issue has happened when I tried to use react-toastify also. So I removed it and used another alternative package.) How to use fonts in the non create-react-app based project?

create-react-app webpack configuration file

I have created a new react app using npx create-react-app and now I want to integrate a webpack.config.js file. I know I don't have to but it is a necessary step for an assignment.
I have tried many tutorials an articles but I can't seem to make it work. All I need is to include all the css related loaders (sass, css etc) and babel.
This is my webpack.config.js file:
const path = require('path');
module.exports = {
mode: "development",
entry: path.join(__dirname,'./src/index.js'),
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
"style-loader",
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader"
]
}
]
},
resolve: {
extensions: ["*", ".js", ".jsx"]
},
output: {
path: path.join(__dirname,'public'),
filename: 'bundle.js'
},
devServer: {
contentBase: path.join(__dirname,'public')
}
};
And I get this error:
ERROR in ./src/index.js 7:16
Module parse failed: Unexpected token (7:16)
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
| import * as serviceWorker from './serviceWorker';
|
> ReactDOM.render(<App />, document.getElementById('root'));
|
| // If you want your app to work offline and load faster, you can change
There're some alternatives that can override webpack config without ejecting the CRA project:
Alternatives You can try customize-cra for a set of CRA 2.0 compatible
rewirers, or any of the alternative projects and forks that aim to
support 2.0:
Rescripts, an alternative framework for extending CRA configurations
(supports 2.0+).
react-scripts-rewired for a fork of this project that
aims to support CRA 2.0
craco
add config-overrides.js in the route and add your webpack changes as:
const { addWebpackModuleRule } = require('customize-cra')
module.exports = {
webpack: override(
addWebpackModuleRule({
issuer: {
test: /\.sass?$/,
},
loader: 'file-loader',
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
}))
}
Answering this just because it kills me to see 10 page Medium articles as an answer when it can be answered in 1 sentence.
Enter your project dir and run npm run eject
This will extract all of the configuration files for you to edit, including webpack.config.js, to a folder called "config". Enter config/webpack.config.js, find the "return" statement, and inside there is a "resolve" configuration option. Add the following to that object:
symlinks: false
Boom. Saved you a stupidly long Medium article.

WebPack 4 fails to load `tsx` file for React: `You may need an appropriate loader to handle this file type.`

Summary:
After creating a React TypeScript application and configuring WebPack 4, I get the following error when it's trying to parse a tsx file:
ERROR in ./src/App.tsx 6:16
Module parse failed: Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
The verbose output doesn't indicate which loader it's attempting to use, nor which file pattern that matched.
How can I troubleshoot this problem?
I opened a bug for shitty error messages here:
https://github.com/webpack/webpack/issues/9025
Here's how to reproduce:
I created a react application like this:
npx create-react-app kontakt-manager --typescript
Then I added this WebPack 4 configuration file, and installed the required packages:
const path = require('path');
module.exports = {
// change to .tsx if necessary
entry: './src/App.tsx',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
// changed from extensions: [".js", ".jsx"]
extensions: ['.ts', '.tsx', '.js', '.jsx']
},
module: {
rules: [
// changed from { test: /\.jsx?$/, use: { loader: 'babel-loader' } },
{ test: /\.(t|j)sx?$/, use: { loader: 'awesome-typescript-loader' } },
// addition - add source-map support
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
]
},
externals: {
"react": "React",
"react-dom": "ReactDOM",
},
// addition - add source-map support
devtool: "source-map"
}
Then I try to package everything:
$ npx webpack --verbose
ℹ 「atl」: Using typescript#3.4.2 from typescript
ℹ 「atl」: Using tsconfig.json from <directory>/tsconfig.json
ℹ 「atl」: Checking started in a separate process...
ℹ 「atl」: Time: 67ms
Hash: 47205d90a8bf0ab03285
Version: webpack 4.29.6
Time: 2404ms
Built at: 2019-04-10 12:13:19 a.m.
2 assets
Entrypoint main = bundle.js bundle.js.map
chunk {0} bundle.js, bundle.js.map (main) 332 bytes [entry] [rendered]
> ./src/App.tsx main
[0] ./src/App.tsx 332 bytes {0} [depth 0] [built] [failed] [1 error]
ModuleConcatenation bailout: Module is not an ECMAScript module
single entry ./src/App.tsx main
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/
ERROR in ./src/App.tsx 6:16
Module parse failed: Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
| class App extends Component {
| render() {
> return (<div className="App">
| <header className="App-header">
| <img src={logo} className="App-logo" alt="logo"/>

How to use Babel without Webpack

I'm making an electron.js using React. I'm using JSX so need to use Babel to transpile. Many tutorials out there all suggests using Webpack.
Currently, I'm using Webpack 4. Here is my webpack.config.js
const path = require('path')
module.exports = {
entry: "./src/renderer.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "renderer.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
}
}
And my .babelrc
{
"presets": ["es2015", "stage-0", "react"]
}
Here I need to start with renderer.js because it contains most of my code and React components, the result is a bundled js file.
But all I want is to transpile all my jsx files to normal js files, something like transpile all JSX files within src to there according JS files in dist folders, and if available, watch and transpile when I edit the files. How to achieve that?
You can simply run babel through the command line:
babel --plugins transform-react-jsx-source script.js
Docs:
https://babeljs.io/docs/plugins/transform-react-jsx-source/
Note the three "Usages" on the page. All of them will get you what you want, none of them use webpack. The .babelrcfile can handle all your plugins/transforms and is the recommended usage. Then you just run babel
Here is an example from Material-UI's package.json:
"build:es2015": "cross-env NODE_ENV=production babel ./src --ignore *.spec.js --out-dir ./build",

Webpack / Babel / React build error: "Unknown option: foo/node_modules/react/react.js.Children"

I'm trying to build a project with webpack and react with this webpack config:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [
'babel-polyfill',
'./app/less/main.less',
'./app/main.js',
'webpack-dev-server/client?http://localhost:8080'
],
output: {
publicPath: '/',
filename: 'dist/main.js'
},
debug: true,
devtool: 'source-map',
module: {
loaders: [
{
test: /\.js$/,
include: path.join(__dirname, 'app'),
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
},
{
test: /\.less$/,
loader: "style!css!autoprefixer!less"
},
]
}
};
I am sure I have the needed pm modules too and have webpack installed, however when running webpack I get:
Module build failed: ReferenceError: [BABEL] /Users/me/foo/app/main.js: Unknown option: foo/node_modules/react/react.js.Children
Any ideas?
Sorry I forgot to install babel-preset-react:
$ npm install babel-preset-react --save-dev
I just wanted to add that I got the error after I uninstalled an old npm module I wasn't using in my project anymore. Which was weird because I wasn't using it anywhere - how could uninstalling something that isn't used anywhere cause an error?
Turns out that one of that modules sub-dependencies had babel-preset-react, which I had missed installing to my own project when I started it. Thus, uninstalling that package also uninstalled the critical babel-preset-react!
For over a year, my react app could compile thanks to another package's sub-dependency...
So yes, installing babel-preset-react solved the issue for me.

Resources