React UnhandledSchemeError - "node:buffer" is not handled by plugins - node.js

I'm trying to use a package in my React project that will allow me to make API calls (axios, node-fetch, got etc.)
When these packages are not installed, the app runs properly. When any of them are installed and called in the code, I'm facing the error as follows:
Ignoring the warnings, I believe the problem has its roots from the output below:
Failed to compile.
Module build failed: UnhandledSchemeError: Reading from "node:buffer" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.
I tried everything. Reinstalled node_modules. Created a clean test app, tried there. Also did my research, didn't find any relevant, clear solution on this. Nothing helped.
What am I doing wrong??
DomException file content:
/*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
if (!globalThis.DOMException) {
try {
const { MessageChannel } = require('worker_threads'),
port = new MessageChannel().port1,
ab = new ArrayBuffer()
port.postMessage(ab, [ab, ab])
} catch (err) {
err.constructor.name === 'DOMException' && (
globalThis.DOMException = err.constructor
)
}
}
module.exports = globalThis.DOMException
npm version: 8.5.5
node version: 16.15.0

You can work around this with this Webpack configuration:
plugins: [
new webpack.NormalModuleReplacementPlugin(/node:/, (resource) => {
resource.request = resource.request.replace(/^node:/, "");
}),
]

Related

Metro has encountered an error: while trying to resolve module "idb-keyval' from file

Trying to connect to a database (back4app) in React Native following this doc: https://www.back4app.com/docs/react-native/parse-sdk/react-native-sdk
I was given this error message:
While trying to resolve module idb-keyval from file /Users/chenhana/TestRegistration/node_modules/parse/lib/react-native/IndexedDBStorageController.js, the package /Users/chenhana/TestRegistration/node_modules/idb-keyval/package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (/Users/chenhana/TestRegistration/node_modules/idb-keyval/dist/compat.cjs. Indeed, none of these files exist:
/Users/chenhana/TestRegistration/node_modules/idb-keyval/dist/compat.cjs(.native|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx|.ios.js|.native.js|.js|.ios.jsx|.native.jsx|.jsx|.ios.json|.native.json|.json)
/Users/chenhana/TestRegistration/node_modules/idb-keyval/dist/compat.cjs/index(.native|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx|.ios.js|.native.js|.js|.ios.jsx|.native.jsx|.jsx|.ios.json|.native.json|.json)
Tried resetting cache, deleting and reinstalling npm modules, and followed along with the doc (also installed the Parse Javascript SDK) so I'm not too sure why this error keeps coming up. Any help will be appreciated, thank you!
In your metro.conf.js file, put the following code:
const { getDefaultConfig } = require("#expo/metro-config");
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push("cjs");
module.exports = defaultConfig;
It might solve the issue
Change your metro.config.js for this:
/**
* Metro configuration for React Native
* https://github.com/facebook/react-native
*
* #format
*/
const defaultSourceExts =
require('metro-config/src/defaults/defaults').sourceExts;
module.exports = {
transformer: {
getTransformOptions: () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
resolver: {
sourceExts: process.env.RN_SRC_EXT
? [...process.env.RN_SRC_EXT.split(',').concat(defaultSourceExts), 'cjs'] // <-- cjs added here
: [...defaultSourceExts, 'cjs'], // <-- cjs added here
},
};

Is there a way to use Vite with HMR and still generate the files in the /dist folder?

First of all, I wanna say that I've started using Vite awhile ago and I'm no Vite expert in any shape or form.
Now, about my problem: I'm working on a Chrome Extension which requires me to have the files generated in the /dist folder. That works excellent using vite build. But, if I try to use only vite (to get the benefits of HMR), no files get generated in the /dist folder. So I have no way to load the Chrome Extension.
If anyone has faced similar issues, or knows a config that I've overlooked, feel free to share it here.
Thanks!
With this small plugin you will get a build after each hot module reload event :
In a file hot-build.ts :
/**
* Custom Hot Reloading Plugin
* Start `vite build` on Hot Module Reload
*/
import { build } from 'vite'
export default function HotBuild() {
let bundling = false
const hmrBuild = async () => {
bundling = true
await build({'build': { outDir: './hot-dist'}}) // <--- you can give a custom config here or remove it to use default options
};
return {
name: 'hot-build',
enforce: "pre",
// HMR
handleHotUpdate({ file, server }) {
if (!bundling) {
console.log(`hot vite build starting...`)
hmrBuild()
.then(() => {
bundling = false
console.log(`hot vite build finished`)
})
}
return []
}
}
}
then in vite.config.js :
import HotBuild from './hot-build'
// vite config
{
plugins: [
HotBuild()
],
}

How can I add ESLInt custom rules directory to VSCode

I am running VSCode with the ESLint plugin. My project contains some custom rules, which live in a particular directory.
If I run ESLint from the command line and pass in --rulesdir=./custom-eslint-rules everything works as expected.
However, I am specifically referring to the linting that happens per file in the editor itself. There, it lints using the normal rules, but shows errors that the definitions for my custom rules are missing.
How can I configure VSCode so that the per-file linting sees my custom rule definitions that live in a particular directory?
In your setting.json:
"eslint.options": {
"rulePaths": "<path>"
}
Reference: https://eslint.org/docs/developer-guide/nodejs-api#cliengine
Write your own eslint plugin and use it with vs code compatibility 🚀
‌
1. install eslint-plugin-rulesdir#0.2.1
yarn add --dev eslint-plugin-rulesdir#0.2.1
2. add to .eslintrc.js
import
const rulesDirPlugin = require("eslint-plugin-rulesdir");
rulesDirPlugin.RULES_DIR = "src/rules"; // it is example
plugins
plugins: [...,"rulesdir"]
rules
rules: {
...,
"rulesdir/no-get-payments": "error"
}
3. create rule file src/rules/no-get-payments.js
module.exports = {
create: function (context) {
return {
CallExpression: function (node) {
if (node.callee.name === "getPayments") {
context.report({
node: node,
message: "getPayments is depricated! ",
});
}
},
};
},
};
‌

Couldn't compile opencv4nodejs in Vue + electron application

I am trying to build a face detection application with opencv4nodejs, vue + electron-builder. During the process of application setup I cam across a problem where I get the following error during npm run serve after installing opencv4nodejs.
Failed to compile.
./node_modules/opencv4nodejs/build/Release/opencv4nodejs.node 1:2
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
It would be great if some one can help me with it. Thank you in advance
Update: I have added my view.config.js for reference
module.exports = {
chainWebpack: config => {
config.module;
// add ts files
// .rule('ts')
// .use('ts-loader')
// .loader('ts-loader')
// .tap(options => {
// modify the options...
// return options
// })
}
};
As our friend #Eldar commented adding node-loader to vue.config.js works for me. Thank you
module.exports = {
chainWebpack: config => {
config.module .rule('ts')
.use('ts-loader')
.loader('ts-loader')
.end()
.rule(/\.node$/)
.use('node-loader')
.loader('node-loader')
.end()
}
};
Hope this is useful folks.

Accessing filesystem in Angular 2 app using Electron

I know that Angular 2 is run on a web browser, which does not have access to the file system.
However, I'm using Electron as my front-end, and also running the app via electron:
"build-electron": "ng build --base-href . && cp src/electron/* dist",
"electron": "npm run build-electron && electron dist"
Therefore, I run it with npm run electron which at the very end runs electron dist.
Since I'm running through electron and not ng I would think that I should be able to access the filesystem. However, when I do:
import * as fs from 'fs'
I get an error:
ng:///AppModule/AppComponent_Host.ngfactory.js:5 ERROR TypeError: __WEBPACK_IMPORTED_MODULE_0_fs__.readFileSync is not a function(…)
Similarly, when I try: var fs = require('fs');
I get:
ng:///AppModule/AppComponent_Host.ngfactory.js:5 ERROR TypeError: fs.readFileSync is not a function
This is the call resulting in the error:
this.config = ini.parse(fs.readFileSync('../../CONFIG.ini', 'utf-8'))
Does anyone have any idea what's causing this?
Thanks.
Solved it by:
1) Eject webpack: ng eject
2) Add target: 'electron-renderer' to the module.exports array inside webpack.config.js
3) Require remote, since we're in the renderer, but fs is only available in the main process (Read more): var remote = require('electron').remote;
4) Require fs (this time using remotes implementation of require): var fs = remote.require('fs');
And now it works!
I am using
Angular CLI: 7.0.7
Node: 8.12.0
OS: win32 x64
Angular: 7.0.4
I tried the ng eject method it didn't work in my case, it is disabled by default and will be removed completely in Angular 8.0
Error message: The 'eject' command has been disabled and will be removed completely in 8.0.
It worked for me by creating a file called native.js in the src folder and insert the following:
`window.fs = require('fs');
Add this file to the angular-cli.json scripts array:
"scripts": [
"native.js"
]
Add the following lines to polyfills.ts:
`declare global {
interface Window {
fs: any;
}
}`
After that you can access the filesystem with:
`window.fs.writeFileSync('sample.txt', 'my data');`
credits
As I understand it, you build the application with Webpack.
You can expose all Node modules via the externals array in your webpack config.
module.exports = {
"externals": {
"electron": "require('electron')",
"child_process": "require('child_process')",
"fs": "require('fs')",
"path": "require('path')",
...
}
}
Since they are provided through the Webpack externals, one does not have to require them but use them with imports.
import * as fs from 'fs'
You can read more about this problem in my article.
I'm late to the party but I also stumbled upon this problem recently. To the late comers, you can use ngx-fs
https://github.com/Inoverse/ngx-fs
Usage:
const fs = this._fsService.fs as any;
fs.readdir("\\", function (err, items) {
if (err) {
return;
}
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
}
});
I had the same problem and could solve it in an easier way:
Just download this project as start, the 'require'-s are already in the webpack.config.js file (along with the integration of angular, electron and so on):
https://github.com/maximegris/angular-electron
import 'fs' into home.ts (or into any other component) as mentioned by #Matthias Sommer above:
import * as fs from 'fs'
Use 'fs' :)

Resources