Unexpected token when trying to load css with webpack and babel - reactjs

I am building a react app using Express,
I tries to add a style loader/css loader to enable importing css,
but when i start my server i get the following error:
M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox>npm run start:dev
> flex_board#1.0.0 start:dev M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox
> cross-env NODE_ENV=development && npm run build:dev && nodemon --exec babel-node -- src/server/server.js
> flex_board#1.0.0 build:dev M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox
> webpack -d
Hash: 1b4953ee761d210e2488
Version: webpack 2.2.1
Time: 2567ms
Asset Size Chunks Chunk Names
bundle.js 2.54 MB 0 [emitted] [big] js
[6] ./~/react/react.js 55 bytes {0} [built]
[23] ./~/react/lib/React.js 2.71 kB {0} [built]
[24] ./~/react-router-dom/es/index.js 2.21 kB {0} [built]
[89] ./~/react-router-dom/es/Link.js 4.67 kB {0} [built]
[94] ./~/react-dom/index.js 58 bytes {0} [built]
[195] ./~/react-router-dom/es/MemoryRouter.js 259 bytes {0} [built]
[196] ./~/react-router-dom/es/NavLink.js 3.36 kB {0} [built]
[197] ./~/react-router-dom/es/Prompt.js 253 bytes {0} [built]
[198] ./~/react-router-dom/es/Redirect.js 255 bytes {0} [built]
[199] ./~/react-router-dom/es/Route.js 252 bytes {0} [built]
[201] ./~/react-router-dom/es/StaticRouter.js 259 bytes {0} [built]
[202] ./~/react-router-dom/es/Switch.js 253 bytes {0} [built]
[203] ./~/react-router-dom/es/matchPath.js 256 bytes {0} [built]
[204] ./~/react-router-dom/es/withRouter.js 257 bytes {0} [built]
[236] ./src/client/app-client.js 706 bytes {0} [built]
+ 222 hidden modules
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `babel-node src/server/server.js`
M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babel-core\lib\transformation\file\index.js:590
throw err;
^
SyntaxError: M:/MainFiles/MyStuff/Code/react/FlexBoardToolBox/src/client/components/Test/text.css: Unexpected token (1:0)
←[0m←[31m←[1m>←[22m←[39m←[90m 1 | ←[39m←[33m.←[39mtest{
←[90m | ←[39m←[31m←[1m^←[22m←[39m
←[90m 2 | ←[39m background←[33m:←[39m blue←[33m;←[39m
←[90m 3 | ←[39m font←[33m-←[39msize←[33m:←[39m ←[35m1.234←[39mpx←[33m;←[39m
←[90m 4 | ←[39m} ←[0m
at Parser.pp$5.raise (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:4373:13)
at Parser.pp.unexpected (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:1716:8)
at Parser.pp$3.parseExprAtom (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3683:12)
at Parser.parseExprAtom (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:7016:22)
at Parser.pp$3.parseExprSubscripts (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3427:19)
at Parser.pp$3.parseMaybeUnary (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3407:19)
at Parser.pp$3.parseExprOps (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3337:19)
at Parser.pp$3.parseMaybeConditional (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3314:19)
at Parser.pp$3.parseMaybeAssign (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:3277:19)
at Parser.parseMaybeAssign (M:\MainFiles\MyStuff\Code\react\FlexBoardToolBox\node_modules\babylon\lib\index.js:6242:20)
[nodemon] app crashed - waiting for file changes before starting...
my package.json file:
{
"name": "flex_board_tools",
"version": "1.0.0",
"description": "tool box",
"main": "server.js",
"scripts": {
"start": "npm run build && babel-node src/server/server.js",
"start:dev": "cross-env NODE_ENV=development && npm run build:dev && nodemon --exec babel-node -- src/server/server.js",
"start:universal": "cross-env UNIVERSAL=true && npm run start",
"start:dev:universal": "cross-env NODE_ENV=development && cross-env UNIVERSAL=true && npm run start:dev",
"build": "cross-env NODE_ENV=production webpack -p",
"build:dev": "webpack -d",
"build:dev:watch": "webpack -d --watch"
},
"author": "Bender",
"license": "MIT",
"dependencies": {
"babel-cli": "^6.18.0",
"babel-core": "^6.18.2",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-2": "^6.24.1",
"ejs": "^2.5.2",
"express": "5.0.0-alpha.5",
"react": "15.4.2",
"react-addons-css-transition-group": "^15.4.0",
"react-dom": "15.4.2",
"react-router-dom": "^4.0.0",
"react-toolbox": "^2.0.0-beta.8"
},
"devDependencies": {
"babel-loader": "^6.4.1",
"babel-register": "^6.18.0",
"cross-env": "^4.0.0",
"css-loader": "^0.28.0",
"eslint": "^3.18.0",
"eslint-config-airbnb": "^14.1.0",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-jsx-a11y": "^4.0.0",
"eslint-plugin-react": "^6.10.3",
"extract-text-webpack-plugin": "^2.1.0",
"isomorphic-style-loader": "^2.0.0",
"nodemon": "^1.11.0",
"style-loader": "^0.16.1",
"webpack": "2.2.1"
}
}
my webpack.config.babel.js
import path from 'path';
const ExtractTextPlugin = require("extract-text-webpack-plugin");
console.log("DIR: " + __dirname);
const config = {
entry: {
js: './src/client/app-client.js',
},
output: {
path: path.join(__dirname, 'src', 'client', 'static', 'js'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: [/\.jsx$/, /\.js$/], //path.join(__dirname, 'src'),
exclude: ["bower_components", "node_modules"],
use: {
loader: 'babel-loader',
options: 'cacheDirectory=.babel_cache',
},
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' }
],
include: [
path.resolve(__dirname, "src","client")
],
}
]
},
plugins: [
]
,
};
export default config;
sample usage (also tried import "./text.css"):
import React from 'react';
import css from './text.css';
export class Test1 extends React.Component {
render() {
return (<div className="test">
Test1 File
</div>
);
}
}
export default Test1;
text.css
.test{
background: blue;
font-size: 1.234px;
}
Ive been at it for hours, cannot seem to find what is wrong.

I had to remove from:
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' }
],
include: [
path.resolve(__dirname, "src","client")
],
}
to:
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' }
],
}
This one works in my case. I don´t know why.

To create npm package, you can build like to:
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: /(node_modules|bower_components|build)/,
loader: 'babel-loader'
},
{
test: /\.(css|less)$/,
use: ["style-loader", "css-loader"]
}
]
},

Since you are rendering your React components which depend on the webpack CSS loader in the backend, on your Express server, you need to run your server-side code through webpack, just as you do your client-side code.
In the project I'm currently working on, I have two webpack builds, each with their own config. One produces a bundle named server.js, the other client.js. In production, I start the server by running node server.js. For local dev, I use a script that rebuilds my server.js when changes in the backend are detected.
It looks like this (file name backend-dev.js):
const path = require('path');
const webpack = require('webpack');
const spawn = require('child_process').spawn;
const compiler = webpack({
// add your webpack configuration here
});
const watchConfig = {
// compiler watch configuration
// see https://webpack.js.org/configuration/watch/
aggregateTimeout: 300,
poll: 1000
};
let serverControl;
compiler.watch(watchConfig, (err, stats) => {
if (err) {
console.error(err.stack || err);
if (err.details) {
console.error(err.details);
}
return;
}
const info = stats.toJson();
if (stats.hasErrors()) {
info.errors.forEach(message => console.log(message));
return;
}
if (stats.hasWarnings()) {
info.warnings.forEach(message => console.log(message));
}
if (serverControl) {
serverControl.kill();
}
// change server.js to the relative path to the bundle created by webpack, if necessary
serverControl = spawn('node', [path.resolve(__dirname, 'server.js')]);
serverControl.stdout.on('data', data => console.log(data.toString()));
serverControl.stderr.on('data', data => console.error(data.toString()));
});
You can start this script on the command line with
node backend-dev.js
When you make changes in your server code, webpack will recompile and restart your server.
Note that I have omitted the actual webpack configuration from the above example, because your mileage will vary. You insert it at the beginning, see code comment.

If you want to use simple css:
import './text.css';
But if you want to use CSS Modules, I assume that according to added CSS in your import, check https://github.com/css-modules/css-modules.
Also, try to change webpack config:
{
test: /\.css$/,
loader: 'style-loader!css-loader!',
},
Check example:
using CSS: https://github.com/Aksana-Tsishchanka/react-routing/blob/master/src/components/Logout.jsx
webpack.config.js: https://github.com/Aksana-Tsishchanka/react-routing/blob/master/webpack.config.js

Try importing your css like that:
import "./text.css";
Please share your css as well.

Related

React+Webpack+Babel: Module parse failed: Unexpected token "<"

I'm setting up a React app (my first), and I've been following this tutorial when I run webpack, I get the following error (pointing to the space immediately before the '<':
PS C:\...\frontend> npm run dev
> frontend#1.0.0 dev C:\...\frontend
> webpack --mode development --entry ./src/index.js --output-path ./build/frontend
asset main.js 4.77 KiB [emitted] (name: main)
runtime modules 937 bytes 4 modules
cacheable modules 1.34 KiB
./src/index.js 34 bytes [built] [code generated]
./src/components/app.js 1.31 KiB [built] [code generated] [1 error]
ERROR in ./src/components/app.js 36:12
Module parse failed: Unexpected token (36:12)
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
| render() {
| return(
> <ul>
| {this.state.data.map(refugee => {
| return (
# ./src/index.js 1:0-34
webpack 5.58.1 compiled with 1 error in 159 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! frontend#1.0.0 dev: `webpack --mode development --entry ./src/index.js --output-path ./build/frontend`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the frontend#1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
As far as I can tell, it's a problem with babel not properly transpiling my app.js file, but for the life of me I can't figure out why it's throwing an error when it gets to the '<' (or maybe the space before the '<'? IDK)
Here's my package.json:
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack --mode development --entry ./src/index.js --output-path ./build/frontend",
"build": "webpack --mode production --entry ./src/index.js --output-path ./static/frontend"
},
"author": "",
"license": "ISC",
"dependencies": {
"#popperjs/core": "^2.10.2"
},
"devDependencies": {
"#babel/core": "^7.15.8",
"#babel/preset-env": "^7.15.8",
"#babel/preset-react": "^7.14.5",
"#babel/preset-stage-3": "^7.8.3",
"babel-cli": "^6.26.0",
"babel-loader": "^8.2.2",
"babel-preset-stage-2": "^6.24.1",
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^6.3.0",
"eslint": "^7.32.0",
"expose-loader": "^3.0.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"set-value": "^4.1.0",
"style-loader": "^3.3.0",
"webpack": "^5.58.1",
"webpack-cli": "^4.9.0",
"webpack-dev-server": "^4.3.1"
}
}
Here's my webpack.config.js:
const Path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const Webpack = require('webpack');
const { WebpackError } = require('webpack');
module.exports = {
entry: {
app: Path.resolve(__dirname,'./src/index.js')
},
output: {
path: Path.resolve(__dirname, './build'),
filename: 'js/[name].js',
},
resolve:{
modules: [Path.join(__dirname,'src'), 'node_modules'],
alias: {
react:Path.join(__dirname,'node_modules','react'),
}
},
optimization:{
splitChunks:{
chunks:'all',
name:'vendors',
}
},
plugins: [
new HtmlWebPackPlugin({
template: Path.resolve(__dirname,'./src/index.html')
}),
// new Webpack.ProvidePlugin({
// $:"jquery",
// jQuery:'jquery',
// Popper:['#popperjs/core','default']
// }),
],
module:{
rules:[
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
'babel-loader',
'style-loader',
"eslint-loader"
],
query: {
presets:["#babel/react", "#babel/env"]
}
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
]
},
{
test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|svg)(\?.*)?$/,
use: {
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
},
},
},
{
test: require.resolve("jquery"),
loader: "expose-loader",
options: {
exposes: ["$", "jQuery"],
},
},
]
}
}
Here's my index.js:
import App from "./components/app"
and my app.js:
import React, { Component } from "react";
import { render } from "react-dom";
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
loaded: false,
placeholder: "loading"
};
};
componentDidMount() {
fetch("api/refugee")
.then(response => {
if (response.status >400) {
return this.setState(() => {
return { placeholder: "Something went wrong!"};
});
}
return response.json();
})
.then(data => {
this.setState(() => {
return {
data,
loaded: true,
};
});
});
}
render() {
return(
<ul>
{this.state.data.map(refugee => {
return (
<li key={refugee.id}>
{refugee.full_name}
</li>
);
})}
</ul>
);
}
}
export default App;
const container = document.getElementById("app");
render(<App />, container);
I am completely at a loss.
FWIW, here's a picture of my directory of my app
Edit:
On a whim, I tried completely removing the module.rules for .js files (instructing webpack to use 'babel-loader', and the error is completely the same. Seems relevant, but I have no idea what it means...
Edit 2:
I forgot to include my .babelrc file:
{
"presets": [
"#babel/preset-env", "#babel/preset-react"
]
}
Edit 3:*
I tried 2 additional things:
I removed the portion of app.js that had <, and the error just pointed to the next < (at render(, container). Webpack ran find when I removed that < as well.
I installed babel-preset-2015 and added ES2015 to my presets in .babelrc. No change in the error message.
Figured it out: I had placed webpack.config.js in the folder webpack/webpack.config.js. I still have no idea how to configure webpack to run if it's placed in a folder within the root directory. Any advice would be appreciated.

"You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file"

I'm trying to compile my React project, but these errors are popping up:
Terminal output:
ERROR in ./src/Components/Info.scss 2:0 Module parse failed:
Unexpected token (2: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
| // ! Styles for Info.js
> .wrapper {
| display: flex;
| flex-direction: column;
# ./src/Components/Info.js 2:0-21
# ./src/Components/App.js 30:0-26 48:465-469
# ./src/index.js 7:0-38 8:50-53
ERROR in ./src/Components/main-style.scss 2:0 Module parse failed:
Unexpected character '#' (2: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
| /* Roboto */
> #import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght#0,400;0,500;1,300&display=swap');
|
| * {
# ./src/Components/App.js 26:0-27
# ./src/index.js 7:0-38 8:50-53
Apparently, something is wrong with my SASS loaders, however I have no idea how to fix this...
My webpack.config.js:
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
const isDevelopment = process.env.NODE_ENV === 'development'
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.[hash].js",
path: path.resolve(__dirname, "dist"),
},
mode: 'development',
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
new MiniCssExtractPlugin({
filename: isDevelopment ? '[name].css' : '[name].[hash].css',
chunkFilename: isDevelopment ? '[id].css' : '[id].[hash].css'
})
],
resolve: {
modules: [__dirname, "src", "node_modules"],
extensions: ["*", ".js", ".jsx", ".tsx", ".ts", ".scss"],
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: require.resolve("babel-loader"),
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.png|svg|jpg|gif$/,
use: ["file-loader"],
},
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
exclude: /node_modules/,
loader: 'file-loader',
options: {
limit: 1024,
name: '[name].[ext]',
publicPath: 'dist/assets/',
outputPath: 'dist/assets/'
}
},
],
},
};
package.json :
{
"name": "finally",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack serve --hot --open",
"build": "webpack --config webpack.config.js --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#babel/core": "^7.14.3",
"#babel/preset-env": "^7.14.2",
"#babel/preset-react": "^7.13.13",
"babel-loader": "^8.2.2",
"html-webpack-plugin": "^5.3.1",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"css-loader": "^5.2.5",
"file-loader": "^6.2.0",
"mini-css-extract-plugin": "^1.6.0",
"node-sass": "^6.0.0",
"sass": "^1.34.0",
"sass-loader": "^11.1.1",
"style-loader": "^2.0.0",
"webpack": "^5.37.1",
"webpack-cli": "^4.7.0",
"webpack-dev-server": "^3.11.2"
}
}
Here's a full terminal output:
i 「wds」: Project is running at http://localhost:8080/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from D:\Web-Development\ScandiWeb\finally
i 「wdm」: wait until bundle finished: /
(node:10768) [DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH] DeprecationWarning: [hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)
(Use `node --trace-deprecation ...` to show where the warning was created)
× 「wdm」: assets by path *.png 28.9 KiB
asset 7fc5201146bcbca270274ca8064944e8.png 16.5 KiB [emitted] [immutable] [from: src/Components/Images/left-arrow.png] (auxiliary name: main)
asset 6ab976a0f3ae89bc5c8a10262caeeb84.png 12.4 KiB [emitted] [immutable] [from: src/Components/Images/right-arrow.png] (auxiliary name: main)
asset bundle.d8670388d44e7af900a1.js 1.42 MiB [emitted] [immutable] (name: main)
asset index.html 458 bytes [emitted]
runtime modules 29.6 KiB 15 modules
modules by path ./node_modules/ 1.29 MiB 34 modules
modules by path ./src/ 18.2 KiB
modules by path ./src/Components/ 16.3 KiB
modules by path ./src/Components/*.js 13 KiB 4 modules
modules with errors 3.08 KiB [errors] 2 modules
modules by path ./src/Components/Images/*.png 160 bytes 2 modules
modules by path ./src/*.css 1.61 KiB
./src/index.css 1.32 KiB [built] [code generated]
./node_modules/css-loader/dist/cjs.js!./src/index.css 298 bytes [built] [code generated]
./src/index.js 315 bytes [built] [code generated]
ERROR in ./src/Components/Info.scss 2:0
Module parse failed: Unexpected token (2: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
| // ! Styles for Info.js
> .wrapper {
| display: flex;
| flex-direction: column;
# ./src/Components/Info.js 2:0-21
# ./src/Components/App.js 30:0-26 48:465-469
# ./src/index.js 7:0-38 8:50-53
ERROR in ./src/Components/main-style.scss 2:0
Module parse failed: Unexpected character '#' (2: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
| /* Roboto */
> #import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght#0,400;0,500;1,300&display=swap');
|
| * {
# ./src/Components/App.js 26:0-27
# ./src/index.js 7:0-38 8:50-53
webpack 5.37.1 compiled with 2 errors in 8467 ms
i 「wdm」: Failed to compile.
Does anyone have any idea on why this can occur?
You need to add your sass loader in your rules:
rules: [
{
test: /\.scss$/,
use: [
"style-loader", // 3. Inject styles into DOM
"css-loader", // 2. Turns css into commonjs
"sass-loader", // 1. Turns sass into css
],
},
];

How to set up babel-plugin-react-css-modules with React?

I am learning React now and I come across the concept of "React CSS Modules". I like the idea of CSS scoping and I want to use it in my code. I found babel-plugin-react-css-modules this plugin to make codes look cleaner. However, I have some problems setting it up in my codes.
Here is my .babelrc file
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
[
"babel-plugin-react-css-modules",
{
"webpackHotModuleReloading": true,
"autoResolveMultipleImports": true
}
]
]
}
My webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
path: path.join(__dirname, "/dist"),
filename: "index_bundle.js",
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
cacheDirectory: true,
},
},
},
{
test: /\.css$/i,
use: [
"style-loader",
{
loader: "css-loader", //generating unique classname
options: {
importLoaders: 1, // if specifying more loaders
modules: true,
sourceMap: false,
localIdentName:
"[path]___[name]__[local]___[hash:base64:5]", //babel-plugin-css-module format
//localIdentName: "[path][name]__[local]" //recommended settings by cssloader#local-scope , this option generate unique classname for compiled css
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
],
};
And my package.json:
{
"name": "react-webpack",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"start": "npx webpack server --mode development --open --hot",
"build": "webpack --mode production"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-plugin-react-css-modules": "^5.2.6",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"#babel/core": "^7.14.0",
"#babel/preset-env": "^7.14.1",
"#babel/preset-react": "^7.13.13",
"babel-loader": "^8.2.2",
"css-loader": "^5.2.4",
"html-webpack-plugin": "^5.3.1",
"postcss-scss": "^3.0.5",
"style-loader": "^2.0.0",
"webpack": "^5.36.2",
"webpack-cli": "^4.7.0",
"webpack-dev-server": "^3.11.2"
}
}
If I do npm start, I get the error:
modules by path ./src/css/*.css 1.42 KiB
./src/css/styles.css 1.38 KiB [built] [code generated]
./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].use[1]!./src/css/styles.css 39 bytes [built] [code generated] [1 error]
./src/index.js 194 bytes [built] [code generated]
./src/components/App.js 388 bytes [built] [code generated]
ERROR in ./src/css/styles.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].use[1]!./src/css/styles.css)
Module build failed (from ./node_modules/css-loader/dist/cjs.js):
ValidationError: Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema.
- options has an unknown property 'localIdentName'. These properties are valid:
object { url?, import?, modules?, sourceMap?, importLoaders?, esModule? }
For more details, I have my code here. I appreciate your help!
BTY, I read the possible solutions here, but no luck.
babel-plugin-react-css-modules is heavily outdated and not maintained;
however there is its up-to-date fork #dr.pogodin/babel-plugin-react-css-modules maintained by me :)

Compilation Issue with a React Login Screen

I've been trying to compile the front end of this guide (git repository here) to get my head round JSX and React. I want to eventually use the code to produce a login screen for a Cordova app.
When trying to compile with webpack, for which I have the following package.json file setup:
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"html-webpack-plugin": "^2.30.1",
"lodash": "^4.17.4",
"react": "^0.14.9",
"react-router-dom": "^4.1.2",
"react-scripts": "^0.8.5",
"router": "^1.3.1",
"script-loader": "^0.7.0",
"superagent": "^3.5.2",
"webpack": "^3.5.4",
"webpack-cordova-plugin": "^0.1.6"
},
"dependencies": {
"axios": "^0.15.3",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-dropzone": "^3.10.0",
"react-file-tree": "0.0.8",
"react-router-dom": "^4.0.0",
"superagent": "^3.4.4"
},
"scripts": {
"start": "webpack-dev-server"
}
}
But when I run webpack index.js run.js in the src folder of the repository, I get the following errors:
Hash: e0d1e2feea6b71367144
Version: webpack 3.5.4
Time: 844ms
Asset Size Chunks Chunk Names
run.js 727 kB 0 [emitted] [big] main
[79] ./index.js 170 bytes {0} [built]
[178] ./App.js 385 bytes {0} [built] [failed] [1 error]
[179] ./index.css 255 bytes {0} [built] [failed] [1 error]
+ 177 hidden modules
ERROR in ./App.js
Module parse failed: C:\Users\Jake\command line work\LearnD\Iteration 0\app\frontend\src\App.js Unexpected token (21:19)
You may need an appropriate loader to handle this file type.
| componentWillMount(){
| var loginPage =[];
| loginPage.push(<LoginScreen appContext={this}/>);
| this.setState({
| loginPage:loginPage
# ./index.js 3:0-24
ERROR in ./index.css
Module parse failed: C:\Users\Jake\command line work\LearnD\Iteration 0\app\frontend\src\index.css Unexpected token (1:5)
You may need an appropriate loader to handle this file type.
| body {
| margin: 0;
| padding: 0;
# ./index.js 4:0-21
It's as if the compiler is treating the code as regular js and not treating it as jsx, despite having the babel-loader in the list of dependencies. Can someone explain to me how I can compile the code?
webpack.config
const path = require('path');
var webpack = require ('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/frontend/src/index.js',
output: {
path: path.resolve('dist'),
filename: 'run.js',
},
module: {
loaders: [{test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/},
{test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/},
{test: /\.js$/, loader: 'lodash-loader', exclude: /node_modules/},
{test: /\.js$/, loader: 'script-loader', exclude: /node_modules/},
{test: /\.jsx$/, loader: 'script-loader', exclude: /node_modules/},
{test: /\.css$/, loader: 'css-loader', exclude: /node_modules/}
]},
plugins: [ new HtmlWebpackPlugin({
template: 'index.template.ejs',
inject: 'body',
})
],
};

Webpack 2.X Not Minifying React App During Production Bundling

I'm having a similar issue to this question which did not seem to get resolved there.
I've finished V1 of my React app and I ran webpack -p to bundle it up for production. The dev version of the bundle is ~2MB and the prod version is the same size. The React dev tools extension confirms I'm still in dev mode and the webpack-bundle-analyzer graphs that React, Chart, and Moment are all > 400kb.
The console output has no errors that I can see.
Anyone run into this issue or know what I'm doing wrong?
webpack.config.js
const path = require('path');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractSass = new ExtractTextPlugin({
filename: 'bundle.css'
});
module.exports = {
context: __dirname,
entry: './client/src/js/App.jsx',
devtool: 'eval',
output: {
path: path.join(__dirname, '/client/dist'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx', '.json', '.scss', 'css']
},
stats: {
colors: true,
reasons: true,
chunks: true
},
module: {
rules: [
{
test: /\.js$/,
loader: 'eslint-loader',
include: path.join(__dirname, '/client/src/js'),
enforce: 'pre'
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, '/client/src/js')
},
{
test: /\.jsx$/,
loader: 'babel-loader',
include: path.join(__dirname, '/client/src/js')
},
{
test: /\.scss$/,
loader: extractSass.extract({
loader: [
{
loader: 'css-loader'
},
{
loader: 'sass-loader'
}
]
})
},
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader'
}
]
}
]
},
plugins: [
extractSass,
new BundleAnalyzerPlugin()
]
};
webpack -p console output
Hash: 8bdf532dc582e2609c1a
Version: webpack 2.6.1
Time: 4904ms
Asset Size Chunks Chunk Names
bundle.js 2.07 MB 0 [emitted] [big] main
bundle.css 8.22 kB 0 [emitted] main
[4] ./~/react/react.js 56 bytes {0} [built]
[18] ./~/react-router-dom/es/index.js 925 bytes {0} [built]
[69] ./~/react-dom/index.js 59 bytes {0} [built]
[230] ./client/src/js/Footer.jsx 324 bytes {0} [built]
[231] ./client/src/js/Home.jsx 431 bytes {0} [built]
[232] ./client/src/js/Hub.jsx 11.4 kB {0} [built]
[233] ./client/src/js/Hubs.jsx 806 bytes {0} [built]
[234] ./client/src/js/Nav.jsx 1.06 kB {0} [built]
[235] ./client/src/js/News.jsx 3.54 kB {0} [built]
[236] ./client/src/js/Overview.jsx 13.8 kB {0} [built]
[237] ./client/src/js/Privacy.jsx 263 bytes {0} [built]
[238] ./client/src/js/Ranks.jsx 6.65 kB {0} [built]
[239] ./client/src/js/TermsConditions.jsx 305 bytes {0} [built]
[240] ./client/src/scss/bundle.scss 41 bytes {0} [built]
[258] ./client/src/js/App.jsx 3.6 kB {0} [built]
+ 422 hidden modules
Child extract-text-webpack-plugin:
[0] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built]
[1] ./~/css-loader!./~/sass-loader/lib/loader.js!./client/src/scss/bundle.scss 8.72 kB {0} [built]
package.json
{
"name": "",
"version": "1.0.0",
"description": "",
"repository": "",
"main": "server.js",
"private": true,
"engines": {
"node": "6.9.5"
},
"scripts": {
"prod": "webpack -p",
"dev": "webpack --watch",
"serve": "nodemon server.js"
},
"author": "",
"dependencies": {
"async": "^2.4.1",
"axios": "^0.16.1",
"body-parser": "^1.15.2",
"dotenv": "^4.0.0",
"express": "^4.14.0",
"mongoose": "^4.8.0",
"nodemon": "^1.11.0",
"path": "^0.12.7"
},
"devDependencies": {
"babel-core": "6.16.0",
"babel-loader": "6.2.7",
"babel-plugin-transform-es2015-modules-commonjs": "^6.18.0",
"babel-polyfill": "^6.16.0",
"babel-preset-es2015": "6.18.0",
"babel-preset-es2017": "6.16.0",
"babel-preset-react": "6.16.0",
"babel-register": "6.16.0",
"chart.js": "^2.6.0",
"css-loader": "0.25.0",
"eslint": "^3.15.0",
"eslint-loader": "1.7.0",
"eslint-plugin-promise": "2.0.1",
"eslint-plugin-react": "6.3.0",
"extract-text-webpack-plugin": "2.1.0",
"jsdom": "9.5.0",
"json-loader": "0.5.4",
"lodash": "4.16.2",
"node-sass": "^4.5.0",
"react": "15.5.4",
"react-chartjs-2": "^2.1.0",
"react-dom": "15.5.4",
"react-router-dom": "^4.1.1",
"sass-loader": "^5.0.1",
"style-loader": "0.13.1",
"webpack": "2.6.1",
"webpack-bundle-analyzer": "^2.8.2",
"yarn": "^0.24.6"
}
}
example component header
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import axios from 'axios';
import Utilities from './Utilities.jsx';
import Header from './Header';
import ChartLine from './ChartLine';
import ChartDoughnut from './ChartDoughnut';
Your issue is devtool: 'eval' line in your Webpack config. Webpack does not automatically disable source maps for production builds; it's on you to check the process.env.NODE_ENV to see if it's in production and disable source maps. Source maps are extremely large (but very useful for development.)
You'll want to change line to be something like devtool: process.env.NODE_ENV === 'production' ? false : 'eval' and set source maps to be false when doing production builds. This should cut 1.5MB+ off your final build.

Resources