I am pretty new to this, but while upgrading to webpack 2 and adding jsx support to my project, I changed the gonfig rules to match what the api calls for in Webpack 2 and added babel-loader. All I am seeing in the browser is "cannot find /".
When I run DEBUG=express:* node index.js
I get:
.../Sites/practice/index.js:1
(function (exports, require, module, __filename, __dirname) { import React from 'react'
^^^^^^
SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:146:18)
at node.js:404:3
webpack.config.js
var webpack = require('webpack')
module.exports = {
entry: './index.js',
output: {
path: 'public',
filename: 'bundle.js',
publicPath: '/'
},
plugins: process.env.NODE_ENV === 'production' ? [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
] : [],
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/],
use: [{
loader: 'babel-loader',
options: { presets: ['es2015', 'react'] },
}],
},
{
test: /\.jsx$/,
exclude: [/node_modules/],
use: [{
loader: 'babel-loader',
options: { presets: ['es2015', 'react'] },
}],
}
]
},
resolve: {
extensions: [
'.jsx',
'.js',
]
},
}
server.js
var express = require('express')
var path = require('path')
var compression = require('compression')
var React = require('react')
var renderToString = require('react-dom/server')
var RouterContext = require('react-router')
var match = require('react-router')
var routes = require('./modules/routes')
var app = express()
app.use(compression())
// serve our static stuff like index.css
app.use(express.static(path.join(__dirname, 'public'), {index: false}))
// send all requests to index.html so browserHistory works
app.get('*', (req, res) => {
match({ routes, location: req.url }, (err, redirect, props) => {
if (err) {
res.status(500).send(err.message)
} else if (redirect) {
res.redirect(redirect.pathname + redirect.search)
} else if (props) {
// hey we made it!
const appHtml = renderToString(<RouterContext {...props}/>)
res.send(renderPage(appHtml))
} else {
res.status(404).send('Not Found')
}
})
})
function renderPage(appHtml) {
return `
<!doctype html public="storage">
<html>
<meta charset=utf-8/>
<title>My First React Router App</title>
<link rel=stylesheet href=/index.css>
<div id=app>${appHtml}</div>
<script src="/bundle.js"></script>
`
}
var PORT = process.env.PORT || 8080
app.listen(PORT, function() {
console.log('Production Express server running at localhost:' + PORT)
})
index.js
import React from 'react'
import { render } from 'react-dom'
import { Router, browserHistory } from 'react-router'
import routes from './modules/routes'
render(
<Router routes={routes} history={browserHistory}/>,
document.getElementById('app')
)
and package.json:
{
"name": "tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
"start:dev": "webpack-dev-server --inline --content-base public/ --history-api-fallback",
"start:prod": "npm run build && node server.bundle.js",
"build:client": "webpack",
"build:server": "webpack --config webpack.server.config.js",
"build": "npm run build:client && npm run build:server"
},
"author": "",
"license": "ISC",
"dependencies": {
"compression": "^1.6.1",
"express": "^4.13.4",
"if-env": "^1.0.0",
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.0"
},
"devDependencies": {
"babel-core": "^6.5.1",
"babel-loader": "^6.2.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.5.0",
"css-loader": "^0.28.0",
"extract-text-webpack-plugin": "^2.1.0",
"http-server": "^0.8.5",
"sass-loader": "^6.0.3",
"static-site-generator-webpack-plugin": "^3.4.1",
"style-loader": "^0.16.1",
"webpack": "^2.2.1",
"webpack-dev-server": "^1.14.1"
}
}
I know i am missing something, but do not know what. I already searched here and tried other suggestions but none of them worked for me.
structure:
-root
-modules
-routes.js
-App.jsx
-othercomponents...
-node_modules
-public
-index.html
-index.css
-data.js
-index.js
-package.json
-server.js
-webpack.config.js
-webpack.server.config.js
-index.js
I think there might be two separate issues:
I am seeing in the browser is "cannot find /".
This looks like an express problem, is the response status 404? In your express server try changing:
app.get('*', (req, res) => {
to:
app.get('/', (req, res) => {
import React from 'react'
SyntaxError: Unexpected token import
This is a node error - node.js does not support ES6 module imports like this. You can change the execution environment to something like babel-node and it should work.
This is actually something I am trying to investigate solutions for - babel-node indicates it is not for production use, but I am having difficulting finding a way to write code in ES6 but use it on the server as well where it is not being processed through a transpiler.
Related
Note: I read through the other similar questions (here and others), but they are all about earlier versions of webpack and babel and do not solve the following issue.
This is serving just fine, but when I run npm run build I'm getting the following error. How do I solve this? (And how do I get better errors than this?, the log is just as bad).
> react_01#1.0.0 build /Users/monkeydo/Documents/code/__tests/react_01
> webpack --mode production
/Users/monkeydo/Documents/code/__tests/react_01/node_modules/webpack-cli/bin/cli.js:41
)} manually.`,
^
SyntaxError: Unexpected token )
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at runCli (/Users/monkeydo/Documents/code/__tests/react_01/node_modules/webpack/bin/webpack.js:69:2)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! react_01#1.0.0 build: `webpack --mode production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the react_01#1.0.0 build script.
My webpack file looks like this:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
//entry: ['#babel/polyfill', './src/index.js'],
entry: './src/index.js',
// Where files should be sent once they are bundled
output: {
path: path.join(__dirname, '/dist'),
filename: 'index.bundle.js'
},
// webpack 5 comes with devServer which loads in development mode
devServer: {
port: 3000,
watchContentBase: true
},
// Rules of how webpack will take our files, complie & bundle them for the browser
module: {
rules: [
{
test: /\.(js|jsx)$/,
// test: /\.jsx?/,
exclude: /nodeModules/,
use: {
loader: 'babel-loader',
query:
{
presets:['react', 'preset-env']
}
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}
]
},
plugins: [new HtmlWebpackPlugin({ template: './src/index.html' }), new MiniCssExtractPlugin()]
}
My package json looks like this:
{
"name": "react_01",
"version": "1.0.0",
"description": "",
"main": "index.jsx",
"scripts": {
"serve": "webpack serve --mode development",
"build": "webpack --mode production"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.14.6",
"#babel/preset-env": "^7.14.7",
"#babel/preset-react": "^7.14.5",
"babel-loader": "^8.2.2",
"css-loader": "^6.0.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2",
"mini-css-extract-plugin": "^2.1.0",
"style-loader": "^3.1.0",
"webpack": "^5.45.1",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
}
My babelrc file looks like this:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
My index.js file looks like this:
import React from "react"
import ReactDom from "react-dom"
import App from "./components/app"
import "./style.css"
ReactDom.render(<App />, document.getElementById('app'))
My app.js file looks like this:
import React from "react"
function App() {
return (<div>
<h2>Welcome to My new React App</h2>
<h3>Date : {new Date().toDateString()}</h3>
</div>)
}
export default App
*** Edit: not sure what I was thinking... I totally forgot to add the webpack code before :o ! I guess that was a dyslexic senior moment. It's added now.
Just remove the styles import
import "./style.css"
Webpack speaks JavaScript, not css, if you want it to learn it you need to create a webpack config file and use the proper loader to handle css
I'm trying to set up ReactJs from scratch but npm start, dev, build, and watch are throwing the error below:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\da4na4\web\stocker\src\index.js: Unexpected character '�' (1:0)
I have setup package.json, webpack.config.js, and .babelrc configurations. I have equally tried out previous answers on Stack Overflow, yet the issue persist. Below are the configurations of the respective files:
package.json
{
"name": "stocker",
"version": "1.0.0",
"description": "A product inventory web app to help you keep track of your stocks and meet demands",
"main": "webpack.config.js",
"scripts": {
"test": "jest ./src/tests",
"dev": "webpack --mode development",
"build": "webpack --mode production",
"watch": "webpack --watch",
"start": "webpack serve --mode development --open --hot"
},
"keywords": [
"products",
"Inventory"
],
"author": "Emmanuel Joshua",
"license": "MIT",
"devDependencies": {
"#babel/core": "^7.12.16",
"#babel/preset-env": "^7.12.16",
"#babel/preset-react": "^7.12.13",
"#webpack-cli/serve": "^1.3.0",
"babel-loader": "^8.2.2",
"css-loader": "^5.0.2",
"html-loader": "^1.3.2",
"html-webpack-plugin": "^5.0.0",
"jest": "^26.6.3",
"jsdom": "^16.4.0",
"sass-loader": "^11.0.1",
"style-loader": "^2.0.0",
"webpack": "^5.21.2",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"react": "^17.0.1",
"react-dom": "^17.0.1"
}
}
webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const htmlPlugin = new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "index.html"
});
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "public"),
filename: "js/app.min.bundle.js",
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(scss|css)$/, use: ["sass-loader", "css-loader", "style-loader"]
},
{
test: /\.(html)$/, use: ["html-loader"]
}
],
},
plugins: [htmlPlugin],
target:"node",
devServer:{
port: 3000,
contentBase: path.resolve(__dirname, "public")
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
};
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
These are the index.js and the App.js files
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './js/App';
ReactDOM.render(
<App firstname={"Joshua"} />,
document.getElementById("root")
)
js/App.js
import React, {Component} from 'react';
class App extends Component{
constructor(props){
super(props);
}
render(){
return(
<h1>Hello {this.props.firstname}, Welcome to our Website!</h1>
)
}
}
export default App;
This tripped me a while. I found out one of the reasons is because of the directory naming path.
I used # for a folder name and it gave me the same error you're reading into.
e.g. my path
C:/Users/johndoes/codes/# wip/project1/sub/
My suggestion is looking at the pathing and seeing if everything is on the right place and referred to correctly.
I'm trying to run my server.js file locally but every time I try "node server.js" I get a:
SyntaxError: Unexpected Identifier for "import React from react
I'm simply trying to see if I get a console.log("connected") message in a function that accesses my database.
I have already tried adding the "transform-es2015-modules-amd" to my plugins in the package.json file in the Babel section. I have tried almost every other solution offered on Stack Overflow posts similar to mine.
package.json
{
"dependencies": {
"atob": "^2.1.2",
"axios": "^0.19.0",
"babel-loader": "^8.0.0-beta.6",
"babel-upgrade": "^1.0.1",
"btoa": "^1.2.1",
"concurrently": "^5.0.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"mysql": "^2.17.1",
"node-fetch": "^2.6.0",
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-redux": "^7.1.1",
"react-router": "^5.1.2",
"react-router-dom": "^5.1.2",
"redux": "^4.0.4",
"request": "^2.88.0",
"serialize-javascript": "^2.1.0"
},
"devDependencies": {
"#babel/cli": "^7.6.4",
"#babel/core": "^7.6.4",
"#babel/node": "^7.6.3",
"#babel/preset-env": "^7.6.3",
"#babel/preset-react": "^7.6.3",
"#types/node": "^12.11.2",
"babel-loader": "^8.0.6",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^3.2.0",
"nodemon": "^1.19.4",
"style-loader": "^1.0.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.9.0",
"webpack-node-externals": "^1.7.2"
},
"babel": {
"presets": [
"#babel/preset-react",
"#babel/preset-env"
]
"plugins": [
"transform-es2015-modules-amd"
]
}
}
server.js
import React from 'react';
import { StaticRouter } from 'react-router-dom';
import { Provider as ReduxProvider } from "react-redux";
import App from '../client/src/App.js';
import { renderToString } from "react-dom/server";
import createStore, { initialize, fetchCharacters } from './store.js';
var path = require("path");
var express = require("express");
var serialize = require("serialize-javascript");
var db = require('./db');
const PORT = process.env.HTTP_PORT || 4001;
const app = express();
app.use('/static', express.static(path.join(__dirname, 'public')));
console.log(__dirname);
app.get('/*', function(req, res) {
const context = {};
const store = createStore();
store.dispatch(initialize());
Promise.all([store.dispatch(fetchCharacters())]).then(() => {
const component = (
<ReduxProvider store={store}>
<StaticRouter location={req.url} context={context}>
<App/>
</StaticRouter>
</ReduxProvider>
);
const ss_react = renderToString(component);
const ss_state = store.getState();
res.writeHead( 200, { "Content-Type": "text/html" });
res.end(htmlTemplate(component, ss_state));
});
});
function htmlTemplate(component, ss_state) {
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React SSR</title>
</head>
`;
}
app.listen(PORT, () => {
console.log(`server listening at port ${PORT}. `);
});
webpack.config.js
const webpack = require('webpack')
const nodeExternals = require('webpack-node-externals')
const path = require('path')
const js = {
test: /\.m?(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader'
}
}
const css = {
test: /\.css$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
modules: true
}
}
]
}
const serverConfig = {
mode: 'development',
target: 'node',
node: {
__dirname: false
},
externals: [nodeExternals()],
entry: {
'index.js': path.resolve(__dirname, 'server/server.js')
},
module: {
rules: [js]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name]'
}
}
const clientConfig = {
mode: 'development',
target: 'web',
entry: {
'index.js': path.resolve(__dirname, 'client/src/index.js')
},
module: {
rules: [js, css]
},
optimization: {
splitChunks: {
chunks: 'all'
}
},
output: {
path: path.resolve(__dirname, 'dist/public'),
filename: '[name]'
}
}
module.exports = [serverConfig, clientConfig]
Node does not understand React JSX. That's what Webpack is for - it uses Babel to transpile your code into vanilla JavaScript.
Looks like you have webpack-dev-server as a dev dependency, so it should already be installed (if you've done an npm install). Make sure you have something like this in your package.json scripts field:
"scripts": {
"start:dev": "webpack-dev-server --config webpack.config.js"
},
Then run npm run start:dev in your console.
Update:
Code pushed to https://github.com/gsouvik/react_spa_experiment
Initial Post:
I know there are hundreds of threads out there, some had typos in webpack config, some used the loaders in a wrong way, some got it solved, some still open. But after numerous tries I still cannot get this working, a simple "Hello World" using Webpack 4, React js.
What I did
I was following this video tutorial line by line:
React & Webpack 4 from scratch
My package.json
{
"name": "my_react_experiment_2",
"version": "1.0.0",
"description": "Basic react with webpack ",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server --mode development --hot",
"build": "webpack --mode production"
},
"author": "Souvik Ghosh",
"license": "ISC",
"dependencies": {
"react": "^16.4.2",
"react-dom": "^16.4.2"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
}
My webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.export = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/build'),
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/templates/index.html'
})
]
};
My .babelrc
{
"presets": ["env", "react"]
}
My directory structure
Expected behaviour
I fire up the dev server npm run dev. Expected to see my shiny new React js page saying "My first React Webpack project" (from the component /components/App.js)
Actual Behavior
ERROR in ./src/index.js 5:16
Module parse failed: Unexpected token (5:16)
You may need an appropriate loader to handle this file type.
| import App from "./components/App";
|
ReactDOM.render(, document.getElementById('root'));
| //ReactDOM.render('Hello User ', document.getElementById('root'));
# multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src main2
If required I can share the codebase via a git repo. Any help is greatly appreciated.
The issue is with typo in your webpack config file.
You have module.export which is not correct. It should be module.exports
Working example
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/build'),
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/templates/index.html'
})
]
};
I'm currently working on a react webpack babel etc site and trying to build the first time. The build is successful, but when I open up the browser I get the following error:
Uncaught Error: Cannot find module "/Users/michael.nakayama/Documents/Development/jamsesh/node_modules/webpack/node_modules/node-libs-browser/node_modules/process/browser.js"
This module exists. Going to that actual url in my browser shows the file in question. But I cannot figure out why webpack cannot find it. I don't know if this is a babel6 issue or a webpack issue, or neither. My config file looks like this:
var webpack = require('webpack');
var cleanWebpack = require('clean-webpack-plugin');
var ignore = new webpack.IgnorePlugin(new RegExp("/(node_modules|ckeditor)/"))
module.exports = {
devtool: 'inline-source-map',
entry: './lib/client/entry',
output: {
path: __dirname + '/public/js',
filename: 'app.js',
publicPath: 'http://localhost:8081/js/',
},
plugins: [
ignore,
],
resolve: {
extensions: ['', '.js'],
moduleDirectories: ['./node_modules']
},
module: {
loaders: [
{
test: /\.js?$/,
loaders: ['babel-loader?presets[]=react,presets[]=es2015,plugins[]=transform-es2015-classes,plugins[]=transform-react-jsx'],
exclude: /(node_modules)/,
}
]
}
}
and my webpack server file is as follows:
var WebpackDevServer = require('webpack-dev-server');
var webpack = require('webpack');
var config = require('../../webpack.config');
var server = new WebpackDevServer(webpack(config), {
// webpack-dev-server options
publicPath: config.output.publicPath,
stats: { colors: true },
});
server.listen(8081, 'localhost', function() {});
and here are the packages I have installed:
"devDependencies": {
"babel-cli": "^6.3.17",
"babel-core": "^6.3.26",
"babel-loader": "^6.2.0",
"babel-plugin-syntax-jsx": "^6.3.13",
"babel-plugin-transform-es2015-classes": "^6.4.0",
"babel-plugin-transform-react-jsx": "^6.3.13",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"body-parser": "^1.14.2",
"clean-webpack-plugin": "^0.1.5",
"express": "^4.13.3",
"history": "^1.17.0",
"jade": "^1.11.0",
"nodemon": "^1.8.1",
"path": "^0.12.7",
"pg": "^4.4.3",
"react": "^0.14.6",
"react-dom": "^0.14.3",
"react-hot-loader": "^1.3.0",
"react-router": "^1.0.3",
"webpack": "^1.12.9",
"webpack-dev-server": "^1.14.0"
}
entry.js:
var React = require('react');
var ReactDOM = require('react-dom');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var routes = require('../routes');
// -v x.13.x
/**Router.run(routes, Router.HistoryLocation, function (Handler, state) {
React.render(<Handler/>, document.getElementById('react-app'));
});**/
var node = document.getElementById('react-app');
// -v 1.0.0
ReactDOM.render(<Router history={createBrowserHistory()} routes={routes}/> , node);
Also as a heads up, I have tried uninstalling and reinstalling all my packages. I have tried installing specifically the node-libs-browser modules. thanks.
The problem with ignore plugin on node_modules. In webpack.config.js, you have:
var ignore = new webpack.IgnorePlugin(new RegExp("/(node_modules|ckeditor)/"))
...
plugins: [
ignore,
],
From Ignore Plugin documentation:
Don’t generate modules for requests matching the provided RegExp.
Webpack tries to require module with the name node_modules/process/browser for React module and fails with it because it is ignored.
Try to remove node_modules from Ignore Plugin or write less global condition if you really need this.
Importing nodeExternals worked for me.
import nodeExternals from 'webpack-node-externals';
this is my server.webpack.config:
import path from 'path';
import nodeExternals from 'webpack-node-externals'; // changes
const CONTEXT = path.join( __dirname, "../.." ),
INPUT_SERVER_DIR = path.join( CONTEXT, "server" ),
OUTPUT_SERVER_DIR = path.join( CONTEXT, "dist/server" );
export default [
{
name: 'server',
target: 'node',
context: INPUT_SERVER_DIR,
node: {
__dirname: false
},
entry: './server',
devtool : 'source-map',
output: {
path: OUTPUT_SERVER_DIR,
filename: "server.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
resolve: {
extensions: ['.js']
},
**externals : [ nodeExternals() ]**
}
];