renderToString causes an Uncaught ReferenceError: require is not defined - javascript

I am currently facing this issue for 3 days and unable to resolve:
Uncaught ReferenceError: require is not defined
at Object.<anonymous> (external "stream":1)
at n (bootstrap:19)
at Object.<anonymous> (react-dom-server.node.production.min.js:10)
at n (bootstrap:19)
at Object.<anonymous> (server.node.js:4)
at n (bootstrap:19)
at Object.<anonymous> (server.js:3)
at n (bootstrap:19)
at Object.<anonymous> (renderer.js:2)
at n (bootstrap:19)
Basically, in my file renderer.js, I have this functionality:
import {renderToString} from 'react-dom/server';
export default (req) => {
let context = {};
const content = renderToString(
<Router location={req.path} context={context}>
<FullPage />
</Router>
);
};
This is the main line which is causing the error basically, this happens when I try to import the renderToString method from 'react-dom/server':
I have tried out different things like removing target: 'node' but none of the solutions worked. What possible might be causing this? I have been stuck on this for the last 3 days and not sure what it is.
My Webpack configuration is:
webpack.base.config.js
module.exports = {
devtool: 'source-map',
module: {
rules: [
{
test: /\.js?$/,
options: {
presets: [
'react', 'stage-2',
['env', { targets: { browsers: ['last 2 versions'] } }]
]
},
loader: 'babel-loader',
exclude: /node_modules/
}
]
}
};
webpack.server.js
const webpack = require('webpack');
const path = require('path');
const SERVER_DIR = path.resolve(__dirname, 'src/server');
const BUILD_DIR = path.resolve(__dirname, 'dist');
const merge = require('webpack-merge');
const baseConfig = require('./webpack.base.config');
const config = {
target: 'node',
entry: SERVER_DIR + '/index.js',
mode: 'production',
output: {
path: BUILD_DIR,
filename: 'bundle.server.js'
}
};
module.exports = merge(baseConfig, config);

Related

SyntaxError: Unexpected token '.' - webpack issue

I have the following error when trying to use a React grid component (from Glide-Data-Grid) in my NextJS project. The error tells me there is an unexpected token '.' in a file inside the nodes_modules folder.
Yet, I tried to use this component in a new React project, in order to see if I have the same error, and everything works well.
How can I fix it in my NextJS project?
Error message:
Image-overlay-editor.js line 16:
My next.config.js:
const { withExpo } = require('#expo/next-adapter');
const withCSS = require('#zeit/next-css');
const withFonts = require('next-fonts');
const withImages = require('next-images');
const withPlugins = require('next-compose-plugins')
const withTM = require('next-transpile-modules')([
'expo-next-react-navigation',
// you can add other modules that need traspiling here
])
module.exports = withPlugins(
[withTM, withFonts, withCSS, withImages, [withExpo, { projectRoot: __dirname }]],
{
webpack: (config, options) => {
config.module.rules.push({
test: /\.js$/,
exclude: /#babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
presets: [
['module:metro-react-native-babel-preset'],
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true }
]
],
plugins: [
['#babel/plugin-transform-flow-strip-types'],
['#babel/plugin-proposal-class-properties']
],
}
});
return config;
}
}
)

Require doesn't appear in my code, but webpack keeps throwing the error "require is not defined."

I'm writing an electron app with react. I run the developement version using this command:
webpack-dev-server --hot --host 0.0.0.0 --port 4000 --config=./webpack.dev.config.js
Here is the webpack.dev.config.js file
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { spawn } = require('child_process');
const helpers = require('./config/helpers');
// Config directories
const SRC_DIR = path.resolve(__dirname, 'src');
const OUTPUT_DIR = path.resolve(__dirname, 'dist');
// Any directories you will be adding code/files into, need to be added to this array so webpack will pick them up
const defaultInclude = [SRC_DIR];
module.exports = {
entry: SRC_DIR + '/index.js',
output: {
path: OUTPUT_DIR,
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
include: defaultInclude
},
{
test: /\.jsx?$/,
use: [{ loader: 'babel-loader' }],
include: defaultInclude
},
{
test: /\.(jpe?g|png|gif)$/,
use: [{ loader: 'file-loader?name=img/[name]__[hash:base64:5].[ext]' }],
include: defaultInclude
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [{ loader: 'file-loader?name=font/[name]__[hash:base64:5].[ext]' }],
include: defaultInclude
}
]
},
target: 'electron-renderer',
plugins: [
new HtmlWebpackPlugin({
template: helpers.root('public/index.html'),
inject: 'body'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
devtool: 'cheap-source-map',
devServer: {
contentBase: OUTPUT_DIR,
stats: {
colors: true,
chunks: false,
children: false
},
setup() {
spawn(
'electron',
['.'],
{ shell: true, env: process.env, stdio: 'inherit' }
)
.on('close', code => {
console.error("electron exited with code ", code);
process.exit(0)
})
.on('error', spawnError => console.error(spawnError));
}
}
};
Once the electron browser opens it has the following error in the Dev-Tools console.
Uncaught ReferenceError: require is not defined
at Object.url (index.js:23)
at __webpack_require__ (bootstrap:709)
at fn (bootstrap:94)
at Object../node_modules/webpack-dev-server/client/utils/createSocketUrl.js (createSocketUrl.js:4)
at __webpack_require__ (bootstrap:709)
at fn (bootstrap:94)
at Object.<anonymous> (client:20)
at Object../node_modules/webpack-dev-server/client/index.js?http://0.0.0.0:4000 (client:176)
at __webpack_require__ (bootstrap:709)
at fn (bootstrap:94)
The place where it claims this is occurring is at index.js:23.
Here is the build version of index.js:
import React from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import App from "./components/App";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { ipcRenderer as ipc } from "electron";
import { onUpdate } from "./actions/workerActions";
import { RECEIVED_STATE } from "./actions/types";
import "./assets/css/index.css";
import rootReducer from "./reducers/rootReducer";
import defaultState from "../config/defaultstate"; //Setup redux store
const middleware = [thunk];
const store = createStore(rootReducer, defaultState, applyMiddleware(...middleware));
ipc.on(RECEIVED_STATE, arg => {
console.log("Recieved State: ", arg);
onUpdate(arg)(store.dispatch);
}); // Now we can render our application into it
render(React.createElement(Provider, {
store: store
}, React.createElement(App, null)), document.getElementById("app"));
As you can see require does not appear here and all of the import aside from ipcRender are designed to run client-side, and therefore should not use required. I tried commenting out the ipcRender import but it resulted in the exact same error.
Most puzzlingly of all, I get the exact same error even with the entire index.js file commented out. The console still claiming the block comment contains a reference to require, which is not defined.
If you're using webpack directly then make sure you have the following in the webpack config that targets your renderer code.
// webpack.config.js
...
module.exports = {
...
target: 'web',
...
}
If you're using Vue then you'll need something like the following:
// vue.config.js
...
module.exports = {
...
configureWebpack: {
target: 'web'
},
...
}
Or, in my case I was using vue-cli-plugin-electron-builder and so need the following:
// vue.config.js
...
module.exports = {
...
pluginOptions: {
electronBuilder: {
nodeIntegration: false,
chainWebpackRendererProcess: config => {
config.target('web');
}
}
},
...
}
It turns out that the error is caused by importing electron's ipcRenderer which requires node integration and uses require. The reason that commenting out the import in the index.js didn't fix the error was because it was imported in other files.

Webpack multi files with dependencies

I use Webpack to create a library to use in all of my projects (both client and server).
This is my webpack.config.js:
const path = require('path');
const libraryName = 'shared';
const config = {
mode: 'development',
entry: {
utils: `${__dirname}/src/shared/utils.js`,
enums: `${__dirname}/src/shared/enums.js`
},
devtool: 'inline-source-map',
output: {
path: `${__dirname}/dist`,
filename: '[name].js',
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true,
globalObject: 'typeof self !== "undefined" ? self : this'
},
externals: {
moment: {
commonjs: 'moment',
commonjs2: 'moment',
amd: 'moment',
root: 'moment'
}
},
module: {
rules: [{
test: /(\.jsx|\.js)$/,
loader: 'babel-loader',
exclude: /(node_modules|bower_components)/
}]
},
resolve: {
modules: [path.resolve('./node_modules'), path.resolve('./src')],
extensions: ['.json', '.js']
}
};
module.exports = config;
This is my enums.js:
import { EnvironmentMode} from './enums/config.enum';
export { EnvironmentMode };
This is my config.enum.js
const { enumUtils } = require('../utils/enum.utils');
// This enum defines the possible environment mode of the application.
const EnvironmentMode = enumUtils.createEnum(new Map([
['DEVELOPMENT', 'development'],
['TEST_LOCAL', 'test_local'],
['TEST_LOCAL_DEMO', 'test_local_demo'],
['TEST_DEMO', 'test_demo'],
['TEST_LINUX', 'test_linux'],
['PRODUCTION', 'production']
]));
module.exports = {
EnvironmentMode: EnvironmentMode
};
This is my utils.js:
import enumUtils from './utils/enum.utils';
export {
enumUtils
};
This is my enum.utils.js
class EnumUtils {
constructor() {}
// This method takes a map of elements and converts them to freeze objects (an enum-like object).
createEnum(mapItems) {
// Check the existence of the mapItems parameter. If not exists, return null instance.
if (!mapItems || mapItems.length <= 0) {
return null;
}
// This new object will hold the freeze array object.
const symbolMap = {};
// Assign each object.
mapItems.forEach((value, key) => {
symbolMap[key] = value;
});
// Freeze the object and return it.
return Object.freeze(symbolMap);
}
}
const enumUtils = new EnumUtils();
module.exports = enumUtils;
For some reason, when I build the project, and inject the compiled code to the projects, run any project, I get the following error:
C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:212
var EnvironmentMode = enumUtils.createEnum(new Map([['DEVELOPMENT', 'development'], ['TEST_LOCAL', 'test_local'], ['TEST_LOCAL_DEMO', 'test_local_demo'], ['TEST_DEMO', 'test_demo'], ['TEST_LINUX', 'test_linux'], ['PRODUCTION', 'production']])); // This enum define the possible error code types that can appear when the server is listening and running.
^
TypeError: Cannot read property 'createEnum' of undefined
at Object../src/shared/enums/config.enum.js (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:212:33)
at __webpack_require__ (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:30:30)
at Object../src/shared/enums.js (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:191:15)
at __webpack_require__ (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:30:30)
at ./src/shared/enums.js.Object.defineProperty.value (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:94:18)
at C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:97:10
at webpackUniversalModuleDefinition (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:3:20)
at Object.<anonymous> (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:10:3)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
What am I doing wrong?
My bad.
I did
const { enumUtils } = require('../utils/enum.utils');
Instead of
const enumUtils = require('../utils/enum.utils');
Fixed it. It works.

Problems after adding 'static-site-generator-webpack-plugin' to my project

I've just added 'static-site-generator-webpack-plugin' to my project and I'm running into the following errors:
ERROR in ReferenceError: window is not defined
at main:1:224
at ContextifyScript.Script.runInContext (vm.js:59:29)
at ContextifyScript.Script.runInNewContext (vm.js:65:15)
at module.exports (/Users/johnnynolan/Repos/css-modules/node_modules/eval/eval.js:69:12)
at /Users/johnnynolan/Repos/css-modules/node_modules/static-site-generator-webpack-plugin/index.js:42:22
at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/johnnynolan/Repos/css-modules/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:7:1)
at AsyncSeriesHook.lazyCompileHook [as _callAsync] (/Users/johnnynolan/Repos/css-modules/node_modules/tapable/lib/Hook.js:35:21)
at hooks.optimizeChunkAssets.callAsync.err (/Users/johnnynolan/Repos/css-modules/node_modules/webpack/lib/Compilation.js:1275:32)
at _err0 (eval at create (/Users/johnnynolan/Repos/css-modules/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:11:1)
at /Users/johnnynolan/Repos/css-modules/node_modules/uglifyjs-webpack-plugin/dist/index.js:282:11
My webpack.config is as follows:
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var StaticSiteGeneratorPlugin = require('static-site-generator-webpack-plugin');
var locals = {
routes: [
'/',
'/about'
]
};
module.exports = {
mode: 'production',
entry: './src',
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
libraryTarget: 'umd' // this is super important
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: __dirname + '/src',
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'),
include: __dirname + '/src'
}
],
},
plugins: [
new StaticSiteGeneratorPlugin('main', locals.routes),
new ExtractTextPlugin("styles.css")
]
};
I'm not sure if this is down to how I've set my webpack.config, however my feeling is that there are issues with using the 'static-site-generator-webpack-plugin' ???
Any help would be much appreciated...
Thanks!
Have you tried adding globalObject: 'this' to your output?
Details here

webpack - output.filename error

I know this is a common question for webpack; it's really hard to debug something if it won't give you any information about the cause or location of the error.
I'm getting the error:
Error: 'output.filename' is required, either in config file or as --output-filename
I know it has to do with a syntax error somewhere, but I'm too new to webpack to figure it out.
Here's my config file. It's called "webpack.config.js" in the root folder (i.e. the folder in which I initially ran: npm init).
const webpack = require('webpack');
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const RewriteImportPlugin = require("less-plugin-rewrite-import");
const root_dir = path.resolve(__dirname)
const src_dir = path.resolve(__dirname, "webpack_src")
const build_dir = path.resolve(__dirname, "webpack_bin")
const node_mod_dir = path.resolve(__dirname, 'node_modules');
const extractLESS = new ExtractTextPlugin('style.css');
const config = {
entry: {
index: path.resolve(src_dir, 'index.js')
},
output: {
path: build_dir,
filename: 'bundle.js'
},
resolve: {
modules: [root_dir, 'node_modules'],
},
module: {
rules: [
{
loader: 'babel-loader',
test: /\.(js)$/
},
{
use: extractLESS.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'less-loader',
options: {
paths: [root_dir, node_mod_dir],
plugins: [
new RewriteImportPlugin({
paths: {
'../../theme.config': __dirname + '/semantic_ui/theme.config',
}
})
]
}
}]
}),
test: /\.less$/
},
{
use: ['file-loader'],
test: /\.(png|jpg|gif|woff|svg|eot|ttf|woff2)$/
},
]
},
plugins: [
extractLESS,
new webpack.optimize.ModuleConcatenationPlugin()
]
};
module.exports = {
config
};
You're exporting module.exports = { config }, which means that you are exporting an object with one property, namely config, but webpack expects the object to be your entire config. Webpack requires output.filename, whereas you only provide config.output.filename.
The export should be your config:
module.exports = config;

Categories