Reputation: 125
I understand this error happens when the require()
function is called in the browser as opposed to within node. However, I can't seem to understand what exactly I need to do to fix this. Any help would be greatly appreciated. You can go to the following repo for whole code base https://github.com/thegreekjester/React_SSR.
Steps to run and reproduce the issue:
localhost:3000
in browser Webpack.client.js
const path = require('path');
const webpackNodeExternals = require('webpack-node-externals');
module.exports = {
// production || development
mode: 'development',
// Inform webpack that we're building a bundle
// for nodeJS, rather then for the browser
target: 'node',
// Tell webpack the root file of our
// server application
entry: './src/client.js',
// Tell webpack where to put the output file
// that is generated
output: {
filename: 'client_bundle.js',
path: path.resolve(__dirname, 'build/public'),
publicPath: '/build/public'
},
module: {
rules: [
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: '/node_modules/',
options: {
presets: [
'react', 'stage-0', ['env', {
target: 'web'
}]
]
}
}
]
}
};
Webpack.server.js
const path = require('path');
const webpackNodeExternals = require('webpack-node-externals');
module.exports = {
// production || development
mode: 'development',
// Inform webpack that we're building a bundle
// for nodeJS, rather then for the browser
target: 'node',
// Tell webpack the root file of our
// server application
entry: './server.js',
// Tell webpack where to put the output file
// that is generated
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
publicPath: '/build'
},
module: {
rules: [
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: '/node_modules/',
options: {
presets: [
'react', 'stage-0', ['env', {
target: { browsers: ['last 2 versions']}
}]
]
}
}
]
},
// Tell webpack not to bundle any libraries that exist in the 'node_modules' folder
// into the server bundle
externals: [webpackNodeExternals()]
};
Upvotes: 1
Views: 4831
Reputation: 3707
In your webpack.client.js
, please remove the key target: 'node'
, because webpack bundling for the client(browser).
In your webpack.server.js
, please add a key libraryTarget: 'commonjs2'
to output
. It would look something like this:
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
publicPath: '/build',
libraryTarget: 'commonjs2',
},
Upvotes: 6