NodeJs : Require is not defined - node.js

I'm using NodeJs and ReactJs, with webpack config.
When I build my app, I have an error on navigator console :
Require is not defined
module.exports = require("jquery");
So I tried to import RequireJs, like this :
var requirejs = require('requirejs');
requirejs.config({
nodeRequire: require,
}),
requirejs (['jquery'])
But I have the same error.
Is there any way to solve the problem?

You're trying to use a CommonJS module from within your browser. This will not work.
ref
Try setting webpack target to web.

module.exports = {
target: 'node',
//externals: [nodeExternals()],
[...]
};

Related

"TypeError: Cannot read property 'indexOf' of undefined" raised when using packages "onoff" or "rpi-gpio" with WebPack

I wrote a Node.JS project for the Raspberry PI, to control the GPIO.
This is my first time using GPIO.
The project uses the "onoff" package to communicate with GPIO. And the compiler is WebPack.
I can compile the project without issue.
But when I run the application on the RaspberryPI, I receive this error:
webpack:///./node_modules/bindings/bindings.js?:178
if (fileName.indexOf(fileSchema) === 0) {
^
TypeError: Cannot read property 'indexOf' of undefined
at Function.getFileName (webpack:///./node_modules/bindings/bindings.js?:178:16)
at bindings (webpack:///./node_modules/bindings/bindings.js?:82:48)
at eval (webpack:///./node_modules/epoll/epoll.js?:7:86)
at eval (webpack:///./node_modules/epoll/epoll.js?:15:3)
at Object../node_modules/epoll/epoll.js (/home/pi/xilium/raspi.node/Raspi.node/dist/raspi.multi-monitor.js:809:1)
at __webpack_require__ (/home/pi/xilium/raspi.node/Raspi.node/dist/raspi.multi-monitor.js:20:30)
at eval (webpack:///./node_modules/rpi-gpio/rpi-gpio.js?:6:20)
at Object../node_modules/rpi-gpio/rpi-gpio.js (/home/pi/xilium/raspi.node/Raspi.node/dist/raspi.multi-monitor.js:1375:1)
at __webpack_require__ (/home/pi/xilium/raspi.node/Raspi.node/dist/raspi.multi-monitor.js:20:30)
at eval (webpack:///./src/raspi.multi-monitor.ts?:29:15)
So, I tried replacing the "onoff" package with "rpi-gpio". Unfortunately, the result is the same.
It seems that there is a configuration issue for "epoll" package (a dependence of "onoff" and "rpi-gpio").
Can anyone help me?
As a disclaimer, I am new to electron, webpack and everything around it, but after a lot of searching, I finally managed to get it working. I am not sure if this is the proper way to do it yet, but I just got it to work.
While searching far and wide, I found this comment on an issue from the serialport package, where they use electron-rebuild to rebuild the serialport module. More info about using native node modules can be found in the Electron documentation here.
Basically, I this to the scripts of my package.json:
"rebuild": "electron-rebuild -f -w onoff"
Then I ran npm run rebuild. Unfortunately, it still didn't work.
What was the missing link, was to tell webpack that the onoff module should be external.
I did it like so, in the webpack config that builds the electron parts of my app (setup is based on this guide I read):
'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
mode: 'development',
entry: './src/electron/main.js',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'out/electron')
},
module: {
rules: []
},
resolve: {
extensions: ['.js']
},
plugins: [
// This is the important part for onoff to work
new webpack.ExternalsPlugin('commonjs', [
'onoff'
])
],
// tell webpack that we're building for electron
target: 'electron-main',
node: {
// tell webpack that we actually want a working __dirname value
// (ref: https://webpack.js.org/configuration/node/#node-__dirname)
__dirname: false
}
};
As I wrote this, I stumbled upon externals config that might just work the same as well.
Now, finally I can blink my LEDs. I hope this answer can help anyone else in the future that might have the same issue.

how to solve the error that fs module is not found when used react and next.js

Am using a react application without router settings. I want to build my sitemap.xml file. I tried some modules like sitemap.js, react-router-sitemap, sitemap-generator. But these module are throwing error as fs module is missing. I installed fs module via npm install --save. But it is still showing the error.
I found in some forums to add the below code in webpack.config file.
node: {
fs: "empty"
}
Am not sure where this file is. I couldn't find them nside the sitemap related modules.
Please help me to resolve this. Am new to react.
Here is my folder structure.
create next.config.js and put below code. It works fine for me.
next.config.js
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
// Important: return the modified config
// Example using webpack option
//config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
config.node = {fs:"empty"}
return config
},
webpackDevMiddleware: config => {
// Perform customizations to webpack dev middleware config
// Important: return the modified config
return config
},
}

Express, Pug and Webpack

I have a Node js server app which uses Express and Pug. I would like to bundle it to single script which can be deployed by pm2. There seem to be several problems with this.
In runtime I get Cannot find module "." and during compilation few messages like
WARNING in ./node_modules/express/lib/view.js 80:29-41 Critical
dependency: the request of a dependency is an expression
appear which come from dynamic imports like require(mod).__express. I assume Webpack can't statically resolve those and does not know which dependency to include.
How can this be solved ?
How do I make Pug compile and be part of the output js ?
It is because webpack rebundle node_modules (already bundled) dependencies and in the case of pug, it doesn't work.
You need to use webpack-node-externals within the webpack externals option in order to specifically ask not to re-bundle depedencies.
Install webpack-node-externals: npm i -D webpack-node-externals
Integrate it your webpack config file:
Example
// ...
const nodeExternals = require('webpack-node-externals')
module.exports = {
target: 'node',
entry: {
// ...
},
module: {
// ...
},
externals: [nodeExternals()],
output: {
// ...
},
}

browserify bundle electron app main process file

I am building a electron app and currently using browserify for the renderer (web page) files like any other javascript front end. I would like to also use browserify to bundle the main process files. However, browswerify is unable to find the electron built in modules like clipboard, ipc, browser-window, app, etc...
In my main.js file which serves as the entry point for the electron app. I have:
const ipc = require('ipc');
const clipboard = require('clipboard');
const BrowserWindow = require('browser-window');
const app = require('app');
const yargs = require('yargs');
the const yargs loads fine as it is in the node_modeuls folder and browserify can resolve that. However the othe four items cannot be found by browserify and therefore fail my build.
[11:49:17] Finished 'development' after 17 ms
Error: Cannot find module 'ipc' from '<path>'
Error: Cannot find module 'clipboard' from '<path>'
Error: Cannot find module 'browser-window' from '<path>'
Error: Cannot find module 'app' from '<path>'
Any suggestions?
With browserify you can set the options 'ignoreMissing' and 'detectGlobals' which allow browserify to ignore built int modules that eventually get loaded automatically in the electron app.
browserify({
entries: './src/main.js',
extensions: ['.js'],
ignoreMissing: true,
detectGlobals: false,
bare: true,
debug: false
})

Resolve the module loaded by plugin in Webpack config

The following example will work only if some-module module is Node module, and won't work for modules loaded by Webpack plugin.
How can Webpack's own logic (enhanced-resolve) be used to resolve module paths in config?
In my case it was bower-webpack-plugin, but I guess this should work in the same way with any ResolverPlugin
var BowerWebpackPlugin = require("bower-webpack-plugin");
module.exports = {
...
module: {
plugins: [new BowerWebpackPlugin()],
loaders: [
{
// this won't work
test: require.resolve("some-bower-module")
loader: "imports?this=>window"
}
]
};
require.resolve inside webpack.config.js is resolved by Node and not Webpack's resolver. You can use require("path").resolve("path/to/bower/module") to get the full path to your Bower module.

Resources