webpack 4 react build causes token error, but run start works - node.js

After a build with webpack I am getting the Uncaught SyntaxError: Unexpected token error. I am able to run start and it will load that way. So I know this must be a problem with the output, or so I would imagine.
The index.html is generating properly, as is the bundle.js. I have that as a path on my index.html file. I am using webpack 4 and have the following webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports ={
entry: './src/index.js',
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js'
},
module: {
rules: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
},
devServer: {
host: 'localhost',
port: '8080'
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
]
}
My .babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties"
]
}
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Expensify</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="src"></div>
<script type="text/javascript" src="bundle.js"></script></body>
</body>
</html>
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { createStore, compose, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import reducer from './store/reducers/auth';
const composeEnhances = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createStore(reducer, composeEnhances(
applyMiddleware(thunk)
));
const app = (
<Provider store={store}>
<App />
</Provider>
)
ReactDOM.render(app, document.getElementById('src'));
Packages.json
{
"name": "reactboilerplate",
"version": "1.0.0",
"description": "React Webpack Redux Babel Boilerplate",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
},
"author": "Thomas Baric",
"license": "ISC",
"dependencies": {
"#babel/core": "^7.2.2",
"#babel/plugin-proposal-class-properties": "^7.3.0",
"#babel/preset-env": "^7.3.1",
"#babel/preset-react": "^7.0.0",
"#material-ui/core": "^3.9.2",
"#material-ui/icons": "^3.0.2",
"axios": "^0.18.0",
"babel-cli": "^6.26.0",
"babel-loader": "^8.0.5",
"babel-plugin-lodash": "^3.3.4",
"babel-plugin-react-transform": "^3.0.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"dateformat": "^3.0.3",
"g": "^2.0.1",
"help": "^3.0.2",
"react": "^16.8.1",
"react-dom": "^16.8.1",
"react-redux": "^6.0.0",
"react-router-dom": "^4.3.1",
"react-slick": "^0.23.2",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"webpack": "^4.29.3",
"webpack-cli": "^3.2.3"
},
"devDependencies": {
"html-webpack-plugin": "^3.2.0",
"webpack-dev-server": "^3.1.14"
}
}

For those wondering this was a backend Django problem regarding static files. Here is my working webpack and babel. This does work on heroku. https://djreactboilertest.herokuapp.com
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports ={
entry: './src/index.js',
output: {
path: path.join(__dirname, 'build', 'static'),
filename: 'bundle.js'
},
module: {
rules: [
{
use: {loader: 'babel-loader'},
test: /\.js$/,
exclude: /node_modules/
}
]
},
devServer: {
host: 'localhost',
port: '8080'
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
]
}
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }]
]
}

Related

Empty page after successful Vercel deployment

What is the problem with my project? I receive an empty page after successful deployment to vercel.
package.json:
{
"name": "currency-converter",
"version": "1.0.0",
"description": "template for react application with typescript",
"main": "index.js",
"homepage": ".",
"license": "MIT",
"scripts": {
"start": "webpack serve --config webpack/webpack.config.js --env env=dev",
"build": "webpack --config webpack/webpack.config.js --env env=prod",
"lint": "eslint \"./src/**/*.{js,jsx,ts,tsx,json}\"",
"lint:fix": "eslint --fix \"./src/**/*.{js,jsx,ts,tsx,json}\"",
"prettier": "prettier \"./src/**/*.{js,jsx,ts,tsx,json,css,scss,md}\"",
"prettier:fix": "prettier --write \"./src/**/*.{js,jsx,ts,tsx,json,css,scss,md}\""
},
"dependencies": {
"babel-loader": "^8.2.5",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"#babel/core": "^7.18.5",
"#babel/plugin-transform-runtime": "^7.18.6",
"#babel/preset-env": "^7.18.2",
"#babel/preset-react": "^7.17.12",
"#babel/preset-typescript": "^7.17.12",
"#babel/runtime": "^7.18.6",
"#pmmmwh/react-refresh-webpack-plugin": "^0.5.7",
"#types/estree": "^0.0.52",
"#types/react": "^18.0.14",
"#types/react-dom": "^18.0.5",
"#typescript-eslint/eslint-plugin": "^5.30.0",
"#typescript-eslint/parser": "^5.30.0",
"copy-webpack-plugin": "^11.0.0",
"css-loader": "^6.7.1",
"eslint": "^8.18.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jsx-a11y": "^6.6.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-react": "^7.30.1",
"eslint-plugin-react-hooks": "^4.6.0",
"html-webpack-plugin": "^5.5.0",
"husky": "^8.0.1",
"lint-staged": "^13.0.3",
"prettier": "^2.7.1",
"react-refresh": "^0.14.0",
"sass-loader": "^13.0.2",
"style-loader": "^3.3.1",
"typescript": "^4.7.4",
"webpack": "^5.74.0",
"webpack-bundle-analyzer": "^4.5.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.9.2",
"webpack-merge": "^5.8.0"
},
"lint-staged": {
"src/**/*.{js,jsx,ts,tsx,json}": [
"eslint --fix"
],
"src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [
"prettier --write"
]
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
}
}
webpack (common config):
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
entry: path.resolve(__dirname, '..', './src/index.tsx'),
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
type: 'asset/resource',
},
{
test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
type: 'asset/inline',
},
],
},
output: {
path: path.resolve(__dirname, '..', './build'),
filename: 'bundle.js',
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '..', './public/index.html'),
}),
new CopyPlugin({
patterns: [{ from: 'src', to: 'dest' }],
}),
],
};
webpack (config):
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
module.exports = ({ env }) => {
const envConfig = require(`./webpack.${env}.js`);
const config = merge(commonConfig, envConfig);
return config;
};
webpack (prod config):
module.exports = {
mode: 'production',
devtool: 'source-map',
};
webpack (dev config):
const ReactRefreshWebpackPlugin = require('#pmmmwh/react-refresh-webpack-plugin');
module.exports = {
mode: 'development',
devtool: 'cheap-module-source-map',
devServer: {
hot: true,
open: true,
},
plugins: [new ReactRefreshWebpackPlugin()],
};
Browser console of deployment:
Warning: DevTools failed to load source map: Could not load content for chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/browser-polyfill.js.map: System error: net::ERR_FILE_NOT_FOUND

Why vue-loader & webpack-4 is not working?

I'm trying to run my own webpack-4 + vue app. with this package.json. I hope if I achieve this I can integrate it with an existing ASP.Net-Core app
{
"name": "client-app",
"version": "1.0.0",
"description": "Proyecto con WebPack 4 y Vue 2",
"main": "index.js",
"scripts": {
"dev": "webpack --config webpack.config.vendor.js --mode development",
"prod": "webpack --mode production"
},
"keywords": [
"webpack-4",
"vue-2",
"vuetify"
],
"license": "ISC",
"devDependencies": {
"autoprefixer": "^9.1.5",
"awesome-typescript-loader": "^5.2.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"base64-font-loader": "0.0.4",
"css-loader": "^1.0.0",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"file-loader": "^2.0.0",
"html-webpack-plugin": "^3.2.0",
"i": "^0.3.6",
"material-design-icons-iconfont": "^3.0.3",
"mini-css-extract-plugin": "^0.4.2",
"postcss-loader": "^3.0.0",
"sass-loader": "^7.1.0",
"typescript": "^2.7.2",
"url-loader": "^1.1.1",
"vue-loader": "^15.4.1",
"vue-class-component": "^6.2.0",
"vue-style-loader": "^4.1.2",
"style-loader": "^0.23.0",
"vue-template-compiler": "^2.5.17",
"webpack-md5-hash": "0.0.6",
"webpack": "^4.17.2",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.7",
"webpack-hot-middleware": "^2.23.1"
},
"dependencies": {
"vue": "^2.5.17",
"vue-router": "^3.0.1",
"vuetify": "^1.2.3",
"vuex": "^3.0.1",
"vuex-class": "^0.3.1"
}
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const bundleOutputDir = 'dist';
const { VueLoaderPlugin } = require('vue-loader')
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
return [{
stats: { modules: false },
context: __dirname,
resolve: { extensions: ['.js'] },
entry: { 'main': './src/index.js' },
module: {
rules: [
{ test: /\.vue\.html$/, include: /ClientApp/, loader: 'vue-loader', options: { loaders: { js: 'awesome-typescript-loader?silent=true', loader: "unicode-loader" } } },
// { test: /\.ts$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
{ test: /\.css$/, use: isDevBuild ? ['style-loader', 'css-loader'] : ExtractTextPlugin.extract({ use: 'css-loader?minimize' }) },
{ test: /\.(png|jpg|jpeg|gif|svg|woff2|woff)$/, include: /ClientApp/, use: 'url-loader?limit=25000' }
]
},
output: {
path: path.join(__dirname, bundleOutputDir),
filename: '[name].js',
publicPath: 'dist/'
},
plugins: [
new VueLoaderPlugin(),
// new CheckerPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: (isDevBuild ? 'development' : 'production')
}
})/* ,
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./dist/vendor-manifest.json')
}) */
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('site.css')
])
}];
};
App.vue
<template>
<div class="example">{{ msg }}</div>
</template>
<script>
export default {
data () {
return {
msg: 'Hello world!'
}
}
}
</script>
<style>
.example {
color: red;
}
</style>
I'm getting the following error:
ERROR in ./src/components/App.vue 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
> <template>
| <div class="example">{{ msg }}</div>
| </template>
# ./src/index.js 2:0-47 11:18-30
Running this command node_modules\.bin\webpack --config webpack.config.js --mode development it should be able to work but it doesn't.
These are specifications:
node: v8.11.2
webpack 4.17.2
vuejs 2.5.17
Anything else you want to know, please tell me.
For anyone else that runs into this issue, newer versions of vue-loader need to be loaded in the webpack plugins section:
// Required for vue-loader v15
const VueLoaderPlugin = require('vue-loader/lib/plugin')
environment.plugins.append(
'VueLoaderPlugin',
new VueLoaderPlugin()
)
From https://github.com/rails/webpacker/issues/1453#issuecomment-412291197
It looks like you don’t have a rule configured for .vue files: you have one for .vue.html files but not for just .vue files. You can just change your existing rule by removing the \.html in order to make it work.

I can't make work webpack correctly

and I got this message, please help... thanks in advance. ...
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.module has an unknown property 'loaders'. These properties are valid:
object { exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, defaultRules?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp?, strictExportPresence?, strictThisContextOnImports? }
-> Options affecting the normal modules (`NormalModuleFactory`).
- configuration.resolve.extensions[0] should not be empty.
-> A non-empty string
my config in webpack is this, I'm still trying to figure out why is this happening ... my file is this: https://github.com/NodeioLabs/Theatherflix/blob/master/webpack.config.js
From line 7-14 and 37-46, you notice this:
resolve: {
root: __dirname,
alias: {
Main: 'app/components/Main.jsx',
Nav: 'app/components/Nav.jsx'
},
extensions: ['', '.js', '.jsx']
},
and
resolve: {
root: __dirname,
alias: {
Main: 'app/components/Main.jsx',
Nav: 'app/components/Nav.jsx',
ListM: 'app/components/ListM.jsx',
About: 'app/components/About.jsx'
},
extensions: ['', '.js', '.jsx']
},
Which is not accepted from the webpack, I suggest you use the recommended from webpack resolve.extensions
resolve.extensions
array
Automatically resolve certain extensions. This defaults to:
extensions: [".js", ".json"]
And here:
root: __dirname,
alias: {
Main: 'app/components/Main.jsx',
Nav: 'app/components/Nav.jsx',
ListM: 'app/components/ListM.jsx',
About: 'app/components/About.jsx'
},
use this format instead as suggested by webpack #resolve-alias
alias: {
Main : path.resolve(__dirname, 'app/components/Main'),
Nav: path.resolve(__dirname, 'app/components/Nav'),
ListM: path.resolve(__dirname, 'app/components/ListM'),
About: path.resolve(__dirname, 'app/components/About')
},
I hope this helps.
Let's look at the messages independently:
configuration.module has an unknown property 'loaders'.
Indicates you currently have:
{
module: {
loaders: {}
}
}
So change loaders to be rules (as per webpack documentation):
{
module: {
rules: {}
}
}
configuration.resolve.extensions[0] should not be empty.
Indicates you have:
{
resolve: {
extensions: ['']
}
}
So remove the empty string from extensions:
{
resolve: {
extensions: []
}
}
I was struggling with the answer ... I had to research a lot. But, I found the answer or I figure out the way out for this kind of situations:
First: create a file .babel-rc
/*
./.babelrc
*/
{
"presets":[
"es2015", "react"
]
}
well consider also this package json file:
{
"name": "theatherflix",
"description": "",
"main": "server.js",
"scripts": {
"webpack": "webpack --progress",
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.config.js"
},
"author": "Nodeio Labs",
"license": "GPL-3",
"dependencies": {
"#babel/preset-react": "^7.0.0-beta.51",
"axios": "^0.18.0",
"babel": "^6.23.0",
"docker": "^1.0.0",
"express": "^4.13.4",
"extract-text-webpack-plugin": "^3.0.2",
"find-process": "^1.1.0",
"loader": "^2.1.1",
"material-ui": "^0.20.1",
"modules": "^0.4.0",
"path": "^0.12.7",
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.0",
"redux": "^4.0.0",
"redux-thunk": "^2.2.0",
"ts-loader": "^4.4.1",
"uuid": "^3.2.1",
"webpack-dev-server": "^3.1.4"
},
"devDependencies": {
"#babel/core": "^7.0.0-beta.51",
"#babel/preset-env": "^7.0.0-beta.51",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.5.0",
"fuse-box": "^3.2.2",
"gulp-babel": "^7.0.1",
"jsx-loader": "^0.13.2",
"node-sass": "^4.9.0",
"typescript": "^2.9.2",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.2"
}
}
*Use what you need in this pack of modules.
Then I correct a few lines in my webpack:
/*
./webpack.config.js
*/
const path = require('path');
module.exports = {
mode: "none",
entry: './app/app.jsx',
output: {
path: path.resolve('public'),
filename: 'bundle.js'
},
module: {
rules: [{
test: /\.css$/,
use: [{
loader: "style-loader"
},
{
loader: "css-loader"
}
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader"
}, {
test: /\.jsx?$/,
exclude: /node_modules/,
use: "babel-loader"
}
]
}
}
And this is my app.jsx :
var React = require('react');
var ReactDOM = require('react-dom');
var {Route, Router, IndexRoute, Main, About, MovieList, hashHistory} = require('react-router');
var Main = require('./components/Main.jsx');
var MovieList = require('./components/MovieList/MovieList.jsx');
var About = require('./components/About/About.jsx');
//import './app.scss';
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Main}>
<Route path="about" component={About}/>
<IndexRoute component={MovieList}/>
</Route>
</Router>,
document.getElementById('app')
);
I hope it might be helpful for others.

Module build failed: ReferenceError: [BABEL] /app/src/index.js: Unknown option: /app/node_modules/react/react.js.Children

My project fails with the error message in title on heroku, but it works locally.
This is my webpack.config.js:
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0']
}
}]
},
resolve: {
extensions: ['.jsx', '.js']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
And this is package.json:
{
"main": "index.js",
"scripts": {
"start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
"test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
"test:watch": "npm run test -- --watch"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.1.18",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"chai": "^3.5.0",
"chai-jquery": "^2.0.0",
"jquery": "^2.2.1",
"jsdom": "^8.1.0",
"mocha": "^2.4.5",
"react-addons-test-utils": "^0.14.7"
},
"dependencies": {
"axios": "^0.17.1",
"lodash": "^3.10.1",
"react": "^0.14.3",
"react-dom": "^0.14.3",
"react-redux": "4.3.0",
"react-router": "^2.0.1",
"react-router-dom": "^4.0.0",
"redux": "^3.0.4",
"redux-form": "^6.6.3",
"redux-promise": "^0.5.3",
"validator": "^9.1.2",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.4"
}
}
I digged around a bit, trying to find an answer, but there was no case such as working on one machine, and not on another machine.
Update 1
Here is index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import promise from 'redux-promise';
import reducers from './reducers';
import LoginForm from './components/login_form';
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<div>
<Route path="/" component={LoginForm} />
</div>
</BrowserRouter>
</Provider>
, document.querySelector('.container'));
** Update 2 **
I tried changing the jsx to js for the test property in webpack loader config object, it didn't help. I removed stage-1 and it's still failing.
This problem got fixed:
Deleted module.query and resolve from the webpack config file.
Moved dependencies from devDependencies to dependencies (heroku is a production environment, and therefore it doesn't download devDependencies, which doesn't make sense to me !)

/src/bundle.js not found in react with webpack application

Below is my server.js file:
import path from 'path';
import express from 'express';
import webpack from 'webpack';
import middleware from './src/middleware';
const app = express();
var port = process.env.PORT || 8080;
if(process.env.NODE_ENV === 'development') {
const config = require('./webpack.config.dev');
const compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
stats: {
assets: false,
colors: true,
version: false,
hash: false,
timings: false,
chunks: false,
chunkModules: false
}
}));
//app.use(require('webpack-hot-middleware')(compiler));
app.use(express.static(path.resolve(__dirname, 'src')));
} else if(process.env.NODE_ENV === 'production') {
app.use(express.static(path.resolve(__dirname, 'dist')));
}
app.get('*', middleware);
app.listen(port, '0.0.0.0', (err) => {
if(err) {
console.error(err);
} else {
console.info(path.resolve(__dirname, 'src'));
console.info('Listening at '+port);
}
});
My webpack.config.dev.js:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/middleware.js',
output: {
path : path.resolve('./src'), // always use absolute paths
filename : 'bundle.js',
publicPath : '/assets/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('development')
}
})
],
module: {
loaders: [
{
test: /\.css$/,
loader: 'style-loader'
}, {
test: /\.css$/,
loader: 'css-loader',
include: path.join(__dirname, 'node_modules'),
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
{
test: /\.js$/,
loader: 'babel',
include: path.resolve(__dirname, 'src'),
query: {
presets: [ 'react-hmre' ]
}
},
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
]
}
};
This is my middleware:
import React from 'react';
import { renderToString } from 'react-dom/server';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { match, RouterContext } from 'react-router';
import reducers from './reducers';
import routes from './routes';
export default (req, res) => {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if(error) {
res.status(500).send(error.message);
} else if(redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if(renderProps) {
res.status(200).send(`
<!DOCTYPE html>
<html>
<head>
<title>Req Management</title>
<link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css">
</head>
<body>
<script src='/src/bundle.js'></script>
<div id='app'>${renderToString(
<Provider store={createStore(reducers)}>
<RouterContext {...renderProps} />
</Provider>
)}</div>
</body>
</html>
`);
} else {
console.log("inside else");
res.status(404).send('Not found');
}
});
};
This is my package.json:
{
"name": "universal-boilerplate",
"version": "1.4.0",
"description": "Universal/isomorphic boilerplate with react, redux, webpack and express",
"main": "src/index.js",
"scripts": {
"lint": "eslint ./src",
"start": "npm run build && cross-env NODE_ENV=development babel-node ./server.js",
"build": "webpack --config ./webpack.config.dev.js",
"serve": "cross-env NODE_ENV=production babel-node ./server.js"
},
"author": "",
"license": "",
"devDependencies": {
"babel-cli": "^6.10.1",
"babel-core": "^6.22.1",
"babel-eslint": "^6.1.2",
"babel-loader": "^6.2.10",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.22.0",
"babel-preset-react-hmre": "^1.1.1",
"babel-preset-stage-0": "^6.5.0",
"copy-webpack-plugin": "^3.0.1",
"cross-env": "^2.0.0",
"eslint": "^3.1.1",
"eslint-plugin-babel": "^3.3.0",
"eslint-plugin-react": "^5.2.2",
"express": "^4.14.0",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"react-redux": "^4.4.5",
"react-router": "^2.6.1",
"react-router-redux": "^4.0.5",
"redux": "^3.5.2",
"rimraf": "^2.5.4",
"webpack": "^1.13.1",
"webpack-dev-middleware": "^1.6.1",
"webpack-hot-middleware": "^2.12.2"
},
"repository": {
"type": "",
"url": ""
},
"dependencies": {
"axios": "^0.13.1",
"babel": "^6.5.2",
"babel-cli": "^6.10.1",
"babel-core": "^6.10.4",
"babel-eslint": "^6.1.2",
"babel-loader": "^6.2.4",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.11.1",
"babel-preset-react-hmre": "^1.1.1",
"babel-preset-stage-0": "^6.5.0",
"copy-webpack-plugin": "^3.0.1",
"cross-env": "^2.0.0",
"eslint": "^3.1.1",
"eslint-plugin-babel": "^3.3.0",
"eslint-plugin-react": "^5.2.2",
"express": "^4.14.0",
"fixed-data-table": "^0.6.3",
"querystring": "^0.2.0",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"react-dropdown": "^1.2.0",
"react-input-autosize": "^1.1.0",
"react-redux": "^4.4.5",
"react-router": "^2.6.1",
"react-router-redux": "^4.0.5",
"react-select": "^1.0.0-rc.3",
"redux": "^3.5.2",
"redux-logger": "^2.6.1",
"redux-thunk": "^2.1.0",
"rimraf": "^2.5.4",
"style-loader": "^0.13.1",
"webpack": "^1.14.0",
"webpack-dev-middleware": "^1.6.1",
"webpack-hot-middleware": "^2.12.2"
}
}
This is my index.js:
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import reducers from './reducers';
import routes from './routes';
import { applyMiddleware, createStore } from "redux"
import logger from "redux-logger"
import thunk from "redux-thunk"
const middleware = applyMiddleware(thunk, logger());
const store = createStore(reducers, middleware);
const history = syncHistoryWithStore(browserHistory, store);
render(
<Provider store={store}>
<Router history={history} store={store}>
{ routes }
</Router>
</Provider>,
document.getElementById('app')
);
if(process.env.NODE_ENV == 'development' && module.hot) {
module.hot.accept('./reducers', () => {
store.replaceReducer(require('./reducers').default);
});
}
I was trying to deploy this code to Heroku. Did some changes in webpack.config.dev.js file. Not able to revert back. Before the code was working fine locally. Now not working locally also.
Folder structure is shown below:
This is probably caused by this:
app.use(express.static(path.resolve(__dirname, 'src')));
This makes src/ the root of your static resources; in other words, /SOME.FILE is looked up as src/SOME.FILE. Extending this to your url, /src/bundle.js, it will be looked up as src/src/bundle.js, which obviously is incorrect.
There are a few solutions:
use /bundle.js instead of /src/bundle.js in the HTML
prefix the path for the static middleware with /src:
app.use('/src', express.static(path.resolve(__dirname, 'src')));
I think the latter would be preferable.
Regarding why your code isn't working locally. it may be because you have a typo. You are checking for:
if(process.env.NODE_ENV === 'develospment') {
Presumably you meant 'development'...

Resources