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

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.

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

I'm trying to build a new react.js project and have a compile error

I'm setting up new react project and I try to compile webpack and had syntax error. In my guesses it is due to package.json and webpack.config.js problem
this is my pacakage.json code
{
"name": "blog_project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"webpack": "webpack"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.5.0",
"#babel/preset-env": "^7.5.2",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.6",
"babel-preset-env": "^1.7.0",
"css-loader": "^3.0.0",
"node-sass": "^4.12.0",
"webpack": "^4.35.3",
"webpack-cli": "^3.3.5"
},
"dependencies": {
"babel-preset-react": "^6.24.1"
"react": "^16.8.6",
"react-dom": "^16.8.6"
}
}
and here is my webpack.config.js code
const path = require('path');
module.exports = {
mode: 'none',
entry: {
app: './src/index.js'
},
watch: true,
devtool: 'source-map',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: [
'.js'
]
}
}
and index.js code I trying to compile and show some div tag on a webbrowser
import React from 'react'
import ReactDOM from 'react-dom'
class RootEl extends React.Component {
render() {
return <div><h1>This is JSX!</h1></div>;
}
}
ReactDOM.render(<RootEl />, document.getElementById("root"))
and when I try to compile this code and then webpack shows me error message
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\blog\blog\static\src\index.js: Unexpected token (7:15)
5 |
6 | render() {
> 7 | return <div>This is XML!</div>;
| ^
8 | }
9 |
10 | }
JSX (like <div> inside javascript) is not a valid javascript syntax. You need babel to transpile those JSX into a valid javascript. To do it, you need to tell babel HOW to transpile those.
You should install #babel/preset-react and set babel up so it will use that preset.
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
['#babel/preset-react'],
],
},
},
]
}
]
},
Presets are basically just a set of rules that babel can refer to when trying to transpile codes.

NPM Self Published Component cannot be found when using it in a React Project

I created my own React component and published it for use.
I just finished minifying for distribution and routing that through webpack.
(Babel used to just transpile and copy all files to dist).
however I now can't seem to import it for my projects anymore.
I install like:
npm i react-subreddit-posts
and then import like:
import SubredditPosts from 'react-subreddit-posts';
And then get this error:
Module not found: Can't resolve 'react-subreddit-posts'
so I must be exporting the module wrong or minifying it wrong???
Here is the source code:
import React, { Component } from 'react';
import ListContainer from './ListContainer';
import ListItemComponent from './ListItemComponent';
const redditAPI = 'https://www.reddit.com/r/';
export default class SubredditPosts extends Component {
constructor(props) {
super(props);
this.state = {
redditPosts: [],
isLoading: true
};
}
componentDidMount() {
const uri = `${redditAPI}${this.props.subreddit}.json`;
fetch(uri)
.then(data => data.json())
.then(this.handlePosts)
.catch(err => console.error(err));
}
handlePosts = (posts) => {
const apiPosts = posts.data.children.map((post, index) => {
return {
key: index,
title: post.data.title,
media: this.getMediaFromPost(post),
link: post.data.url
};
});
this.setState({
redditPosts: apiPosts,
isLoading: false
});
}
getMediaFromPost = (post) => {
const extension = post.data.url.split('.').pop();
if (post.data.hasOwnProperty('preview') && !extension.includes('gif')) {
return post.data.preview.images[0].source.url;
}
//do not use includes! because of Imgur's gifv links are not embeddable
if (extension === 'gif' || extension.includes('jpg') || extension.includes('jpeg')) {
return post.data.url;
}
//if can't load media then place placeholder
return this.props.placeholder;
}
render() {
return(
<ListContainer display={this.props.display}>
{ !this.state.isLoading && this.state.redditPosts.map(post => (
<ListItemComponent
display={this.props.display}
key={post.key}
link={post.link}
media={post.media}
title={post.title}
height={this.props.height}
width={this.props.width}
/>
))}
</ListContainer>
);
}
}
Here is what is in node_modules after install through npm:
I can export it just fine from the src, but not when it's published and distributed!
Package.json:
{
"name": "react-subreddit-posts",
"version": "1.0.12",
"description": "React component for displaying subreddit posts in different styles",
"main": "dist/main.js",
"repository": {
"type": "git",
"url": "https://github.com/stcalica/react-subreddit-posts"
},
"directories": {
"example": "example"
},
"scripts": {
"test": "jest",
"start": "webpack-dev-server --mode development",
"transpile": "rm -rf dist && webpack",
"prepublishOnly": "npm run transpile",
"compile": "webpack --config ./webpack.config.js --progress"
},
"jest": {
"setupTestFrameworkScriptFile": "./test/setupTest.js"
},
"keywords": [
"react",
"reddit"
],
"author": "Kyle Calica",
"license": "ISC",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-jest": "^23.0.1",
"babel-loader": "^7.1.4",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-es2015-arrow-functions": "^6.22.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.11",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"html-webpack-plugin": "^3.2.0",
"jest": "^23.1.0",
"react": "^16.4.0",
"react-dom": "^16.4.0",
"react-test-renderer": "^16.4.1",
"style-loader": "^0.21.0",
"uglifyjs-webpack-plugin": "^1.2.5",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {}
}
webpack.config.js
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// const htmlWebpackPlugin = new HtmlWebpackPlugin({
// template: path.join(__dirname, 'example/src/index.html'),
// filename: './index.html'
// });
module.exports = {
entry: path.join(__dirname, 'example/src/index.js'),
output: {
libraryTarget: 'commonjs2',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['react'],
plugins: ['transform-class-properties']
}
}
]
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
// plugins: [ htmlWebpackPlugin ],
resolve: {
extensions: ['.js', '.jsx']
},
devServer: {
port: 3001
}
};
In your github I saw that you have the dist path in your .gitignore file but if you see your package.json you would see that your repo is pointing to the dist/index.js file which does not exist because you added it to the .gitignore.
Try:
Remove the exclusion in your gitignore
Recompile your app and create the dist folder
Publish it again in npm
Re-download your dependency by npm/yarn install
And make sure you got the latest version of your dependency

webpack not bundling with babel-loader and react

I am following along with a relatively older tutorial (from 2014) on RGR. I had to use an updated version of React, Webpack, and Babel so there are some differences. Everything has been working thus far except when I tried to compile JSX into webpack, it is giving me a build error.
ERROR in ./public/js/app.js
Module build failed: SyntaxError: Unexpected token (7:15)
5 | class Hello extends React.Component {
6 | render() {
7 | return <h3>Hello Webpack!</h3>;
| ^
8 | }
9 | }
10 |
Below is my React file:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
class Hello extends React.Component {
render() {
return <h3>Hello Webpack!</h3>;
}
}
ReactDOM.render(<Hello />, document.getElementById('react'));
and this is my webpack.config.js file
module.exports = {
entry: "./public/js/app.js",
output: {
path: __dirname + "/public",
filename: "bundle.js"
},
module: {
loaders: [
{test: /\.js$/,
loader: 'babel-loader' }
]
}
}
Also, here is my package.json file
{
"name": "rgrjs",
"version": "1.0.0",
"description": "a collection of educational resources about React, GraphQL, and Relay",
"main": "index.js",
"scripts": {
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/krisxcrash/rgr-stack.git"
},
"author": "kristine martin",
"license": "ISC",
"bugs": {
"url": "https://github.com/krisxcrash/rgr-stack/issues"
},
"homepage": "https://github.com/krisxcrash/rgr-stack#readme",
"dependencies": {
"babel-loader": "^7.1.2",
"create-react-class": "^15.6.2",
"express": "^4.16.2",
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1"
}
}
Can anyone tell me why it is not reading the <h3> after return and causing an error when webpack is trying to bundle?
You're missing some presets:
First do npm install:
npm install babel-core babel-preset-es2015 babel-preset-react --save-dev
Also make a .babelrc in your root project directory, and include this:
{
"presets": ["es2015","react"]
}
Also in your loaders section of webpack config, include this for jsx:
{ test: /\.jsx?$/, exclude: /node_modules/, use: ['babel-loader'] }

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