Node.js/Redux/Express error - node.js

I am teaching myself to use Nodejs with Redux and Express. I have a tag in my view, and that's it. Very, very basic. I am getting an error in my console that I don't understand:
Uncaught ReferenceError: process is not defined
at Object.<anonymous> (bundle.js:548)
at __webpack_require__ (bundle.js:20)
at Object.defineProperty.value (bundle.js:492)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:482)
at __webpack_require__ (bundle.js:20)
at __webpack_exports__.b (bundle.js:63)
at bundle.js:66
Can someone help me figure out what this means?
Here is my server.js file:
"use strict"
var express = require('express');
var app = express();
var path = require('path');
// MIDDLEWARE TO DEFINE FOLDER FOR STATIC FILES
app.use(express.static('public'))
app.get('/', function(req, res){
res.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})
app.listen(3000, function(){
console.log('app is listening');
})
Here is my app.js file:
"use strict"
import {createStore} from 'redux'
// STEP 3 define reducers
const reducer = function(state=0, action){
switch(action.type){
case "INCREMENT":
return state + action.payload;
break;
}
return state
}
// STEP 1 create the store
const store = createStore(reducer);
store.subscribe(function(){
console.log('current state is: ' + store.getState());
})
// STEP 2 create and dispatch actions
store.dispatch({type: "INCREMENT", payload: 1 })
Here is my webpack.config.js file:
var path = require('path');
const webpack = require('webpack');
module.exports = {
entry: ['./src/app.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public')
},
target: 'node',
watch: true,
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}
]
}
}

Try adding this code to the plugin portion of your webpack.config
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production") //or "development"
}
});
You can read about why this might be your issue below. Basically you need to give webpack a NODE_ENV variable.
https://github.com/facebook/react/blob/f7850dd3d78d313a9e7774870e85c32719fbe233/docs/docs/getting-started.md

Related

Express router: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string

I know I am struggling in this problem.
I am working on a webpack Universal React App but i got this error message and I have no idea where it come from:
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received type function ([Function (anonymous)])
at new NodeError (node:internal/errors:372:5)
at Function.from (node:buffer:323:9)
at ServerResponse.send (C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\response.js:193:22)
at eval (webpack://isomorphic-react-redux-router-app/./app/serverside/server.js?:17:19)
at Layer.handle [as handle_request] (C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\router\layer.js:95:5)
at C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\router\index.js:284:15
at Function.process_params (C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\router\index.js:346:12)
I think it is because of the url on the eval argument:
webpack://isomorphic-react-redux-router-app/./app/serverside/server.js?:17:19
Having a relative path in the middle of the url is not good.
Here are my webpack file:
const path = require('path');
require("core-js/stable");
require("regenerator-runtime/runtime");
const nodeExternals = require('webpack-node-externals');
module.exports = [
{
mode: 'development',
stats: {warnings:false},
target:'web',
entry: {
'/bundle-app': ['core-js','regenerator-runtime/runtime','./app/clientside/client.jsx']
},
output: {
path: path.resolve(__dirname, 'build/dev'),
filename: '[name].js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.jpe?g|png$/,
exclude: /node_modules/,
use: ["url-loader", "file-loader"]
},
{
test: /\.(jsx|js)$/,
include: path.resolve(__dirname, '/'),
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
}]
}
]
},
},
{
name: 'server',
mode: 'development',
target: 'node',
stats: {warnings:false},
externals: [nodeExternals()],
entry: {
'/server/bundle-server': ['core-js','regenerator-runtime/runtime','./app/serverside/server.js'],
},
output: {
path: path.resolve(__dirname, 'build/dev'),
filename: '[name].js',
},
plugins: [],
module: {
rules: [
{
test: /\.(jsx|js)$/,
include: path.resolve(__dirname, '/'),
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
}]
},
]
}
}
]
my express server file:
import express from 'express';
import serverRenderer from './renderSSR.js';
import cors from 'cors';
let app = express();
app.use(cors());
app.use(express.urlencoded({extended:false}));
app.use(express.json());
app.get('/', (req, res) => {
res.status(200).send(serverRenderer());
}); // when the user connect to the root of the server we send the page
app.listen(8080, () => console.log("Example app listening on port 8080!"));
import { renderToString } from 'react-dom/server';
import fs from 'fs';
import App from '../src/App.jsx';
export default function serverRenderer() {
return (req, res, next) => {
const html = renderToString( // on rend côté serveur du pur HTML
<StaticRouter location={req.url}>
<App/>
</StaticRouter>
);
// we read the index.html page and we change the div to insert the app content
fs.readFile('../html/index.html', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
// after succefuly read the html file, we insert the App component content
var htmlApp = data.replace('<div id="app">','<div id="app">' + html);
return htmlApp;
});
};
}
my client file:
// principal programme côté client, est capable de faire du rendue HTML, sera appelé une deuxième par le client.
import * as React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router} from 'react-router-dom';
import App from '../src/App.jsx';
ReactDOM.render(
<Router>
<App/>
</Router>,
document.getElementById('root')
); // on rend le react dans l'element HTML root
and finally my commun App file:
import React from 'react';
import ReactDOM from 'react-dom';
export default function App(props)
{
return (
<p>Hello App!</p>
)
};
Where does the problem come from?
How to fix it?
Thanks in advance for your responses.
The answer from Heiko TheiBen solve my problem.
Thanks for your attention!

webpack build failed

I am building an app with react in the front end and nodejs on the backend . y react is packed by webpack and configure my server to run concurrently with the front end. For months, i have been building my app successfully, suddenly my build begins to fail throwing warnings like below followed by errors
WARNING in ./server/~/sequelize/lib/sequelize.js Critical
dependencies: 388:61-74 the request of a dependency is an expression
# ./server/~/sequelize/lib/sequelize.js 388:61-74
And errors like
ERROR in ./server/models/index.js Module not found: Error: Cannot
resolve module 'fs' in /PATH/static/server/models
My webpack used to be config like below
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: ['babel-polyfill', 'react-hot-loader/patch', path.normalize(__dirname + '/src/index')],
devtool: 'cheap-module-source-map',
devServer: {
hot: true
},
output: {
filename: 'bundle.js',
publicPath: '/',
path: path.join(__dirname, 'server')
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
loader: 'style!css',
test: /\.css$/,
include: [path.resolve(__dirname, 'public', 'css')]
},
{
test: /\.json$/,
loader: "json-loader"
}
],
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
//'process.env.NODE_ENV': JSON.stringify('development')
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
}
};
ANd my server config below
var webpack = require('webpack');
var config = require('./webpack.config');
var path = require('path');
var express = require('express');
var app = express();
const http = require('http');
const port = process.env.PORT || 3000;
var compiler = webpack(config);
require('./server/config/express')(app, port, compiler, config);
const server = http.createServer(app);
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.code || 500)
.json({
status: 'error',
message: err
});
});
}
app.use(function (err, req, res, next) {
res.status(err.status || 500)
.json({
status: 'error',
message: err.message
});
});
server.on('close', () => {
models.sequelize.close();
});
My server config above is based in server folder and i wasn't expecting my webpack to build that folder. My build has being working fine for months until 3 days when it suddenly stopped throwing the errors above. It occurs to me that it is building/packaging the server folder which i wasn't expecting.
I then update my babel-loader to
{
loader: 'babel-loader',
test: /\.js$/,
exclude: [/node_modules/, /server/]
}
yet to no avail. I am really confused on how i can best configure this. My development suddenly stopped. Pls any help would be appreciated.
It turns out a colleague mistakenly referenced/imported a file from the server folder hence the issue. The line
import { authenticateUser } from '../../../server/controllers/user';
in one of the components in the src folder caused that.

Having some trouble setting up my webpack config

I am following a few tutorials, but mainly the one by Dan Abramov on setting up react hot loader but I am having some issues. I think I have a basic configuration working, however hot reloading of component does not seem to work, so obviously the hot loader set up is wrong :(
When I change a component, my browser console logs this:
The following modules couldn't be hot updated: (Full reload needed)
This is usually because the modules which have changed (and their parents) do not know how to hot reload themselves. See http://webpack.github.io/docs/hot-module-replacement-with-webpack.html for more details.
- ./app/components/Home/index.jsx
To start off, here is my file structure:
.
|++[app]
|----[actions]
|----[modules]
|----[reducers]
|----[store]
|----index.html
|----index.js
|--[config]
|----server.js
|----webpack.config.js
|--[node_modules]
|--package.json
Here's my webpack config:
var webpack = require('webpack');
var path = require('path');
var autoprefixer = require('autoprefixer');
var isProd = process.env.NODE_ENV === 'production';
module.exports = {
devtool: isProd ? null : 'source-map',
entry: [
'webpack-hot-middleware/client',
path.resolve('app/index.js')
],
output: {
path: path.resolve('dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
root: path.resolve( 'app/'),
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: [
'babel'
],
include: path.resolve('.'),
exclude: /node_modules/
},
{
test: /\.(png|jpg)$/,
loader: 'file-loader?name=img/[name].[ext]'
},
{
test: /\.scss$/,
loader: 'style!css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]!postcss!sass'
}
]
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin()
],
postcss: [
autoprefixer({ browsers: ['last 3 versions'] })
]
};
And my server.js
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var config = require('./webpack.config');
var path = require('path');
var app = new (require('express'))();
var port = 3000;
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
app.get('/*', function(req, res) {
res.sendFile(path.resolve('app/index.html'));
});
app.listen(port, function(error) {
if (error) {
console.error(error);
} else {
console.info('started on localhost://%s.', port);
}
});
The react-hot loader is missing within your module.loaders array. More into this.
Next we need to tell Webpack to use React Hot Loader for the components. If you configured Webpack for React, you may already use babel-loader (ex 6to5-loader) or jsx-loader for JS(X) files. Find that line in webpack.config.js and put react-hot before other loader(s).
So you need to add the react-hot loader before your babel loader, like so:
{
test: /\.jsx?$/,
loader: 'react-hot',
exclude: /node_modules/
}
And also you need to install the react-hot-loader module if you haven't already.
npm i -D react-hot-loader

Cannot find entry module in webpack using nodejs API

I am trying to run webpack from within nodejs. My directory structure looks like this:
build
|- dev.js
dist
|- bundle.js
src
|- layout
|- App.js
|- server
|- app.js
dev.js:
const webpack = require('webpack');
const path = require('path');
// returns a Compiler instance
const compiler = webpack(
{
context: path.resolve(__dirname, '../src'),
entry: [
'./server/app.js'
],
output: {
path: path.join(__dirname, '../dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader?presets[]=es2015&presets[]=react'
}
]
}
}
);
compiler.run(function(err, stats) {
if(err) {
console.log('Err');
}
});
app.js:
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import App from '../layout/App';
const app = express();
app.get('*', (req, res) => {
res.send(renderToString(<App />));
});
app.listen(3000, () => {
});
If I now run node build/dev.js it generates my bundle.js, but it does not find my entry module.
(function webpackMissingModule() { throw new Error("Cannot find module \"./server/app.js\""); }());
Even though I think this is how the entry point should be defined, I have tried many combinations, even the absolute path. But always the same result, it cannot find the entry module. What am I missing here?
It looks like something is going wrong with bundling the assets - since webpack looks in your node_modules to find its assets it, would be best if you could post your package.json alongside the other files.
You're using webpack programatically instead of the default webpack command, which normally gives a lot of debug output (along with information about the build-steps, errors, etc.) - I would suggest using that to debug it, and then switch to the programmatical approach when you know that everything is working.
It looks like you want to do server-side rendering with react. Some special configuration is needed for your webpack configuration then. This is already handled here: http://jlongster.com/Backend-Apps-with-Webpack--Part-I
Without having the package.json it is really hard to debug exactly what goes wrong here.
Assuming your package.json is correct, here's a dev.js file that would work with the above code:
const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
// returns a Compiler instance
const compiler = webpack(
{
context: path.resolve(__dirname, "../src"),
target: 'node',
entry: [
'./server/app.js'
],
output: {
path: path.join(__dirname, '../dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader?presets[]=es2015&presets[]=react'
}
]
},
externals: nodeModules
}
);
compiler.run(function(err, stats) {
console.log(err, stats);
});

webpack exception when using express middleware router

I have a simple webpack with react hotloader & express setup and working. I'm trying to add an external node module that will register a sub router for some services. For some reason, doing so causes a strange exception (see below).
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config');
var app = express();
var router = express.Router();
var mod = require("my-module");
mod.registerServices(router); // <-- adds routes to the router
app.use("/api/v1*", router); // <-- This line causes the error
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
stats: {
colors: true
}
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(3000, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:3000');
});
The Exception:
$ node server.js
/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51
throw new Error('locals[0] does not appear to be a `module` object with Hot Module ' + 'replacement API enabled. You should disable react-transform-hmr in ' + 'production by using `env` section in Babel configuration. See the ' + 'example in README: https://github.com/gaearon/react-transform-hmr');
^
Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration. See the example in README: https://github.com/gaearon/react-transform-hmr
at Object.proxyReactComponents [as default] (/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51:11)
at Object.<anonymous> (/Users/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/components/simple.js:25:60)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/containers/CompanyLocationPage.js:13:25)
at Module._compile (module.js:434:26)
UPDATE
Turns out that removing this from .babelrc where I have some react transforms enabled and subsequently removing all of the web pack hotloader plugins & middleware gets the router working again.
{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}
Try this solution: don't use babel-plugin-react-transform in .babelrc, use config in webpack.config.js
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
include: path.join(__dirname, 'src'),
query: {
plugins: [
["react-transform", {
transforms: [{
transform: "react-transform-hmr",
imports: ["react"],
locals: ["module"]
}]
}]
]
}
}
]
}
Details:
https://github.com/gaearon/babel-plugin-react-transform/issues/62
https://github.com/gaearon/react-transform-hmr/issues/5

Resources