Webpack 2.X Not Minifying React App During Production Bundling - reactjs

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.

Related

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 :)

Why am I getting this 'Property 'Item' does not exist on type '(...args: any[]) => any' error in my webpack build output?

I'm trying to set up a project that uses webpack, typeScript, react, and semantic-ui-react.
When I run yarn run start, I get the following errors:
yarn run v1.3.2
$ webpack --config webpack.prod.babel.js
clean-webpack-plugin: /home/nathan.jones/Projects/my_project/dist has been removed.
Hash: fe11c4f68633b60f3925
Version: webpack 3.10.0
Time: 33566ms
Asset Size Chunks Chunk Names
images/icons.svg 444 kB [emitted] [big]
fonts/icons.eot 166 kB [emitted]
fonts/icons.woff2 77.2 kB [emitted]
fonts/icons.woff 98 kB [emitted]
fonts/icons.ttf 166 kB [emitted]
images/flags.png 28.1 kB [emitted]
vendor.c818f10aeab0f3bfd9d1.js 418 kB 0 [emitted] [big] vendor
app.7b83116ba71a9fcf8e82.js 1.38 kB 1 [emitted] app
manifest.7d42facf685791692fbd.js 1.42 kB 2 [emitted] manifest
styles.css 566 kB 1 [emitted] [big] app
index.html 684 bytes [emitted]
[145] (webpack)/buildin/module.js 517 bytes {0} [built]
[371] multi react react-dom semantic-ui-react 52 bytes {0} [built]
[419] (webpack)/buildin/global.js 509 bytes {0} [built]
[723] ./src/index.tsx 2.42 kB {1} [built] [4 errors]
+ 732 hidden modules
ERROR in ./src/index.tsx
[tsl] ERROR in /home/nathan.jones/Projects/my_project/src/index.tsx(29,12)
TS2339: Property 'Item' does not exist on type '(...args: any[]) => any'.
ERROR in ./src/index.tsx
[tsl] ERROR in /home/nathan.jones/Projects/ezrodeo/src/index.tsx(12,15)
TS2339: Property 'Item' does not exist on type '(...args: any[]) => any'.
ERROR in ./src/index.tsx
[tsl] ERROR in /home/nathan.jones/Projects/ezrodeo/src/index.tsx(14,16)
TS2339: Property 'Item' does not exist on type '(...args: any[]) => any'.
When I take out the references to Menu.Item, the error goes away.
Here are my webpack configs.
webpack.common.babel.js
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import webpack from 'webpack';
export default {
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.(ttf|eot|woff|woff2)$/,
loader: "file-loader",
options: {
name: "fonts/[name].[ext]",
},
},
{
test: /\.(png|svg)$/,
loader: "file-loader",
options: {
name: "images/[name].[ext]",
},
},
]
},
plugins: [
new ExtractTextPlugin('styles.css'),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity,
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest'
}),
],
resolve: {
extensions: ['.tsx', '.ts', '.js', '.css']
},
};
webpack.prod.babel.js
import merge from 'webpack-merge';
import UglifyJSPlugin from 'uglifyjs-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';
import webpack from 'webpack';
import path from 'path';
import common from './webpack.common.babel.js';
export default merge(common, {
entry: {
vendor: [
'react',
'react-dom',
'semantic-ui-react',
],
app: './src/index.tsx'
},
plugins: [
new CleanWebpackPlugin(['dist']),
new UglifyJSPlugin({
sourceMap: true
}),
new HtmlWebpackPlugin({
title: 'EZ Rodeo',
template: 'src/index-prod.html'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
],
output: {
filename: '[name].[chunkhash].js',
path: path.resolve(__dirname, 'dist')
}
});
package.json
{
"name": "my_project",
"version": "0.1.0",
"description": "Project description",
"main": "index.js",
"scripts": {
"build": "webpack --config webpack.prod.babel.js",
"start": "webpack-dev-server --open --config webpack.dev.babel.js"
},
"devDependencies": {
"#firebase/app-types": "^0.1.0",
"#types/react": "^16.0.34",
"babel-core": "^6.26.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-register": "^6.26.0",
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.28.8",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^1.1.6",
"html-webpack-plugin": "^2.30.1",
"name-all-modules-plugin": "^1.0.1",
"react-hot-loader": "^3.1.3",
"style-loader": "^0.19.1",
"ts-loader": "^3.2.0",
"typescript": "^2.6.2",
"uglifyjs-webpack-plugin": "^1.1.6",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.11.0",
"webpack-merge": "^4.1.1"
},
"dependencies": {
"firebase": "^4.8.1",
"mobx": "^3.4.1",
"mobx-react": "^4.3.5",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router-dom": "^4.2.2",
"semantic-ui-css": "^2.2.12",
"semantic-ui-react": "^0.77.2"
}
}
src/index.tsx
import 'semantic-ui-css/semantic.min.css';
import * as React from 'react';
import * as ReactDOM from 'react-dom'
import { Menu } from 'semantic-ui-react';
export default class MenuExampleBasic extends React.Component {
render() {
return (
<Menu>
<Menu.Item>
Editorials
</Menu.Item>
</Menu>
)
}
}
ReactDOM.render(<MenuExampleBasic />, document.getElementById('root'));
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true
}
}
.babelrc
{
"presets": ["env"],
"plugins": ["react-hot-loader/babel"]
}
index-prod.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div id="root"></div>
</body>
</html>
the --module=es6 compiler option is what's tripping typescript trying to resolve semantic-ui-react. I'm not sure why, but removing it will let webpack finish without errors.

Angular 1.6 with web-pack and es6 module compiled successfully but not running in browser

I am trying to develop angular 1.6 with es6 . syntax and using web pack and yarn with help of this article and when execute yarn run start , webpack compiled successfully but when open localhost:8080/ in the browser it says can not get /
here is the relevant code
webpack.config.js
const path = require('path');
const BUILD_DIR = path.resolve(__dirname, 'public');
const APP_DIR = path.resolve(__dirname, 'src');
const config = {
context : __dirname,
entry: APP_DIR + '/app/app.js',
output: {
path: BUILD_DIR ,
filename: "bundle.js",
publicPath: '/'
},
devtool : 'cheap-module-inline-source-map',
devServer: {
inline: true,
historyApiFallback: true,
hot: true,
contentBase: "./public"
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: { presets: ['env'] }
},
{ test: /\.html$/, loader: "html" },
{
test: /\.less$/,
loader: "style-loader!css-loader!less-loader"
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.inline.svg$/,
loader: 'babel-loader!svg-react-loader'
},
{
test: /\.jpe?g$|\.gif$|\.png$|^(?!.*\.inline\.svg$).*\.svg$/,
loader: 'url-loader'
},
{
test: /\.(woff2?|eot|ttf)$/i,
loader: 'url-loader'
}
]
},
resolve: {
extensions: [ '.html', '.js', '.json', '.css', '.less']
}
};
module.exports = config;
package.json
{
"name": "es6angular",
"version": "0.0.0",
"description": "Es6 System",
"dependencies": {
"angular": "^1.6.7",
"angular-animate": "^1.6.7",
"angular-aria": "^1.6.7",
"angular-bootstrap": "^0.12.2",
"angular-chart.js": "^1.1.1",
"angular-messages": "^1.6.7",
"angular-resource": "^1.6.7",
"angular-sanitize": "^1.6.7",
"angular-toastr": "^2.1.1",
"angular-ui-router": "^0.4.3",
"angular-ui-sortable": "^0.18.0",
"angular-ui-validate": "^1.2.3",
"bootstrap": "^3.3.7",
"fontawesome": "^4.7.2",
"gulp": "^3.9.1",
"international-phone-number": "^0.0.11",
"intl-tel-input": "^12.1.6",
"jquery": "^3.2.1",
"moment": "^2.19.4",
"ng-table": "^3.0.1",
"ngstorage": "^0.3.11",
"roboto-fontface": "^0.8.0"
},
"scripts": {
"start": "webpack-dev-server --hot"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-env": "^2.4.1",
"babel-eslint": "^8.0.3",
"babel-loader": "^7.1.2",
"babel-preset-minify": "^0.2.0",
"css-loader": "^0.28.7",
"eslint": "^4.13.1",
"eslint-config-airbnb-base": "^12.1.0",
"eslint-plugin-angular": "^3.1.1",
"eslint-plugin-html": "^4.0.1",
"eslint-plugin-import": "^2.8.0",
"file-loader": "^1.1.5",
"html-webpack-plugin": "^2.30.1",
"less": "^2.7.3",
"less-loader": "^4.0.5",
"path": "^0.12.7",
"style-loader": "^0.19.1",
"svg-inline-loader": "^0.8.0",
"url-loader": "^0.6.2",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.9.7"
},
"engines": {
"node": ">=0.10.0"
}
}
app/app.js
'use strict';
import 'bootstrap/dist/css/bootstrap.css';
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import ngMessages from 'angular-messages';
import uiBootstrap from 'angular-bootstrap';
import routing from './app.config';
import home from './home';
angular
.module('app', [ngMessages, uiRouter, uiBootstrap, home])
.config(routing);
app/index.html
<!doctype html>
<html ng-app="app" lang="en">
<head>
<meta charset="utf-8">
<title>Angular ES6</title>
<meta name="description" content="Application Manager">
<meta name="viewport" content="width=device-width">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body class="top-navigation" >
<ui-view></ui-view>
<script src="bundle.js"></script>
</body>
</html>
app/app.config.js
routing.$inject = ['$urlRouterProvider', '$locationProvider'];
export default function routing($urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
}
home/home.controller.js
export default class HomeController {
constructor() {
this.name = 'World';
}
changeName() {
this.name = 'angular-tips';
}
}
home/home.route.js
routes.$inject = ['$stateProvider'];
export default function routes($stateProvider) {
$stateProvider
.state('home', {
url: '/',
templateURL: './home.html',
controller: 'HomeController',
controllerAs: 'home'
});
}
home/home.html
<div class="jumbotron">
<h1>Hello, {{home.name}}</h1>
</div>
<button class="btn btn-primary" ng-click="home.changeName()">Change</button>
home/index.js
import angular from 'angular';
import uirouter from 'angular-ui-router';
import routing from './home.route';
import HomeController from './home.controller';
export default angular.module('app.home', [uirouter])
.config(routing)
.controller('HomeController', HomeController).name;
other files can be found here in this URL, although this file is not running but only contains the code
What is wrong in this?
below is yarn run start log in terminal
warning package.json: No license field
$ webpack-dev-server --hot
Project is running at http://localhost:8080/
webpack output is served from /
Content not from webpack is served from ./public
404s will fallback to /index.html
Hash: b429c9fda4e99e95ee12
Version: webpack 3.10.0
Time: 2243ms
Asset Size Chunks Chunk Names
bundle.js 6.16 MB 0 [emitted] [big] main
[0] (webpack)/hot/log.js 1.04 kB {0} [built]
[4] (webpack)/hot/emitter.js 77 bytes {0} [built]
[7] ./node_modules/angular-ui-router/release/angular-ui-router.js 175 kB {0} [built]
[8] multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/app/app.js 52 bytes {0} [built]
[9] (webpack)-dev-server/client?http://localhost:8080 7.95 kB {0} [built]
[10] ./node_modules/url/url.js 23.3 kB {0} [built]
[17] ./node_modules/strip-ansi/index.js 161 bytes {0} [built]
[19] ./node_modules/loglevel/lib/loglevel.js 7.86 kB {0} [built]
[20] (webpack)-dev-server/client/socket.js 1.05 kB {0} [built]
[22] (webpack)-dev-server/client/overlay.js 3.73 kB {0} [built]
[29] (webpack)/hot/dev-server.js 1.61 kB {0} [built]
[31] ./src/app/app.js 921 bytes {0} [built]
[41] ./node_modules/angular-messages/index.js 62 bytes {0} [built]
[43] ./node_modules/angular-bootstrap/ui-bootstrap-tpls.js 143 kB {0} [built]
[45] ./src/app/home/index.js 657 bytes {0} [built]
+ 33 hidden modules
webpack: Compiled successfully.

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',
})
],
};

Unexpected token when trying to load css with webpack and babel

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.

Resources