Can't resolve 'fs' in electron-react-boilerplate app - reactjs

colleagues,
I have encountered with 2 errors. Tried many solutions found in stackoverflow and www but nothing helped. I would appreciate much if you provide any suggestions.
ERROR in ./src/component/FileReaderComponent.tsx 8:11-24
Module not found: Error: Can't resolve 'fs' in 'D:\apps\ex-electron-react\src\component'
# ./src/renderer/App.tsx 8:30-73
# ./src/renderer/index.tsx 10:30-46
ERROR in ./src/component/FileReaderComponent.tsx 9:13-28
Module not found: Error: Can't resolve 'path' in 'D:\apps\ex-electron-react\src\component'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
# ./src/renderer/App.tsx 8:30-73
# ./src/renderer/index.tsx 10:30-46
Have node-16.15.0 and npm-8.5.5
Installed electron-react-boilerplate
Dependencies in package.json are:
"electron-debug": "^3.2.0",
"electron-log": "^4.4.7",
"electron-updater": "^5.0.1",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-router-dom": "^6.3.0"
BrowserWindow in main.ts has
webPreferences: {
preload: app.isPackaged
? path.join(__dirname, 'preload.js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
Created a react component
import { Component } from "react";
const fs = require("fs");
const path = require("path");
export class FileReaderComponent extends Component<any, any> {
setTabletImages = () => {
fs.readdirSync('.').forEach( (file: string) => {
const extname = path.extname( file );
const filename = path.basename( file, extname );
const absolutePath = path.resolve( 'D:\\geo\\tablets\\9x7\\temp', file );
console.log( "File : ", file );
console.log( "filename : ", filename );
console.log( "extname : ", extname );
console.log( "absolutePath : ", absolutePath);
});
}
render() {
return (
<button onClick={this.setTabletImages}>
<span>Log filenames</span>
</button>
);
}
}
repo in github
UPD 1
If I changes BrowserWindow in main.ts
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload: app.isPackaged
? path.join(__dirname, 'preload.js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
The issues will gone away, module fs is able to be imported but
I receive another error:
Unable to load preload script: .erb\dll\preload.js
(anonymous) # node:electron/js2c/renderer_init:73
node:electron/js2c/renderer_init:73 Error: contextBridge API can only be used when contextIsolation is enabled
at node:electron/js2c/renderer_init:45:277
at Object.exposeInMainWorld (node:electron/js2c/renderer_init:45:359)
at preload.ts:5:15
at preload.ts:21:4
at Object.<anonymous> (preload.ts:21:4)
at Object.<anonymous> (preload.ts:21:4)
at Module._compile (node:internal/modules/cjs/loader:1116:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10)
at Module.load (node:internal/modules/cjs/loader:988:32)
at Module._load (node:internal/modules/cjs/loader:829:12)
UPD 2
I tried to add a line fallback: { "fs": false, path: false }, to webpack.config.base.ts the error after launch have gone but when onClick event is emitted the compiler returns error fs.readdirSync is not a function.

Following https://electron-react-boilerplate.js.org/docs/native-modules/
and https://webpack.js.org/configuration/externals/
helped me resolve the same issue for fsevents
added:
const configuration: webpack.Configuration = {
externals: [...Object.keys(externals || {}), 'fsevents'],
...
...
to my webpack.config.base.ts

Related

puppeteer-core problem! Can't resolve 'fs', 'http'

I am making web scraping site,
and I want get Tags in URL , but they are dynamic sources.
so I can't touch only Cheerio.
people recommended Puppeteer. and my problem was starting
first. I could see Module not found:
Error: Can't resolve 'https' in '/Users/Documents/myMac/Study/bookMarks/node_modules/puppeteer-core/lib/cjs/puppeteer/node'
and also they couldn't find out os, path .....
so I add (I use yarn) webpack and cli
second. I set the webpack.config.js for fallback
resolve:{
fallback:{
"fs":false,
"os": require.resolve("os-browserify/browser"),
"path": require.resolve("path-browserify"),
"https": require.resolve("https-browserify"),
"stream": false,
"zlib": false ,
"crypto": false,
"constants": false,
}
}
because the Err-Message said
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "https": require.resolve("https-browserify") }'
- install 'https-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "https": false }
but the err messages still there when I yarn start
Third. I thought if the config didn't set .
so I did ' $ webpack --config webpack.config.js'
I couldn't see the err
but still when I did yarn start, problem are there
4th. I add fs, os, http..... (in the err's module name) using yarn
I can see the dependencies
"os": "^0.1.2", "path": "^0.12.7",
and added
"browser": {
"crypto": false,
"fs": false,
"path": false,
"os": false,
"net": false,
"stream": false,
"tls": false
}
setting in package.json
but,,
.
.
.
ERROR in ./node_modules/puppeteer-core/lib/cjs/puppeteer/node/FirefoxLauncher.js 43:29-42
Module not found: Error: Can't resolve 'fs' in '/Users/Documents/myMac/Study/bookMarks/node_modules/puppeteer-core/lib/cjs/puppeteer/node'
ERROR in ./node_modules/puppeteer-core/lib/cjs/puppeteer/node/ProductLauncher.js 65:13-26
Module not found: Error: Can't resolve 'fs' in '/Users/Documents/myMac/Study/bookMarks/node_modules/puppeteer-core/lib/cjs/puppeteer/node'
webpack compiled with 41 errors
I am having 41 errors
5th . I removed folder the node_modules and yarn.lock
and did
$ yarn cache clean $ yarn install
it doesn't work
also I removed puppeteer-core and re-add
and i have 41 errors still
do you have another way
or
can I alternate puppeteer?
at last
this is js module using puppeteer
const puppeteer = require('puppeteer-core');
const DomParser = require('dom-parser');
async function getTagList(url) {
const tagListText = new Array();
try{
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
const html = await page.content();
const parser = new DomParser();
const dom = parser.parseFromString(html);
const tagList = dom.getElementsByClassName('tag_area')[0].getElementsByTagName('a');
tagListText = Array.from(tagList).map(tag => tag.textContent);
await browser.close();
}catch(error) {
console.error(error);
}
return tagListText;
}
module.exports = { getTagList };
and I am using chatGPT. he recommended setting in webpack.config.js
Specially fallback -> fallbacks
and it can't terminal said fallbacks isn't option
I use webpack5

AssertionError [ERR_ASSERTION]: [MFSU] package.json not found for dep config/loginSettings which is imported from #/app.ts

This is the loginSettings.tsx file recently add into the project:
import { Settings as LayoutSettings } from '#ant-design/pro-layout';
import routes from './routes';
const LoginSettings: LayoutSettings & {
pwa?: boolean;
logo?: string;
} = {
navTheme: 'light',
primaryColor: '#1890ff',
layout: 'mix',
contentWidth: 'Fluid',
fixedHeader: false,
fixSiderbar: true,
colorWeak: false,
title: 'Red Dwarf',
pwa: false,
logo: '/icons/icons/OSX/Images.xcassets/AppIcon.appiconset/MacHuge_512pt.png',
iconfontUrl: '',
menu:{
request:async (params, defaultMenuData) => {
return routes;
}
}
};
export default LoginSettings;
when I import the loginSettings.tsx into the project. compile show error:
Bundle with webpack 5...
⏱️ MFSU Enabled
Starting the development server...
✖ Webpack
Compiled with some errors in 1.60s
ERROR Failed to compile with 1 errors 12:43:36 PM
error in ./src/app.tsx
Module build failed (from ./node_modules/#umijs/deps/compiled/babel-loader/index.js):
AssertionError [ERR_ASSERTION]: [MFSU] package.json not found for dep config/loginSettings which is imported from #/app.tsx
at getDepVersion (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/umi/node_modules/#umijs/preset-built-in/lib/plugins/features/mfsu/getDepVersion.js:129:27)
at DepInfo.addTmpDep (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/umi/node_modules/#umijs/preset-built-in/lib/plugins/features/mfsu/DepInfo.js:141:56)
at Object.onTransformDeps (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/umi/node_modules/#umijs/preset-built-in/lib/plugins/features/mfsu/mfsu.js:327:23)
at PluginPass.exit (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/#umijs/babel-plugin-import-to-await-require/lib/index.js:217:140)
at newFn (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/#umijs/deps/compiled/babel/bundle.js:62022:21)
at NodePath._call (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/#umijs/deps/compiled/babel/bundle.js:56841:20)
at NodePath.call (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/#umijs/deps/compiled/babel/bundle.js:56828:17)
at NodePath.visit (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/#umijs/deps/compiled/babel/bundle.js:56887:8)
at TraversalContext.visitQueue (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/#umijs/deps/compiled/babel/bundle.js:56353:16)
at TraversalContext.visitSingle (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/#umijs/deps/compiled/babel/bundle.js:56322:19)
at TraversalContext.visit (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/#umijs/deps/compiled/babel/bundle.js:56381:19)
at Function.traverse.node (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/#umijs/deps/compiled/babel/bundle.js:56506:17)
at traverse (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/#umijs/deps/compiled/babel/bundle.js:56486:12)
at transformFile (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/#umijs/deps/compiled/babel/bundle.js:6224:29)
at transformFile.next (<anonymous>)
at run (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/#umijs/deps/compiled/babel/bundle.js:6152:12)
● Webpack █████████████████████████ done (99%)
plugins
why did this happen? This is how I import this config in app.tsx file:
import LoginSettings from 'config/loginSettings';

Can't resolve 'url' in node_modules error when trying to access Azure Key Vault with React

I'm new to React and Azure, I'm trying to get a secret value from Azure [Key Vault]. I'm getting this compile error.
I'm using: "#azure/identity": "^2.0.4", "#azure/keyvault-secrets": "^4.4.0"
import React, { useState } from 'react';
import { SecretClient } from "#azure/keyvault-secrets";
import { DefaultAzureCredential } from "#azure/identity";
export const KV = () => {
const [secret, setSecret] = useState("");
const credential = new DefaultAzureCredential();
const client = new SecretClient("https://xxx.vault.azure.net/", credential);
client.getSecret("secretKey").then(res => { setSecret(res); });
return <>{secret}</>
}
I'm getting this error message:
ERROR in
./node_modules/#azure/keyvault-secrets/dist-esm/keyvault-common/src/parseKeyvaultIdentifier.js
3:0-27 Module not found: Error: Can't resolve 'url' in
'xxx\node_modules#azure\keyvault-secrets\dist-esm\keyvault-common\src'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it. If you want to
include a polyfill, you need to:
add a fallback 'resolve.fallback: { "url": require.resolve("url/") }'
install 'url' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "url": false }
<Add "lib": ["dom"] to your tsconfig.json, or simply add dom to an existing array in the lib property>, but I'm not using typescript. How do I do this in react?
You can find tsconfig.json inside the root folder of your react project.
If you don't have tsconfig.json, you can create the same and add "lib":["dom"] to it.
For example:
{
"extends": "../../../tsconfig.package",
"compilerOptions": {
"declarationDir": "./types",
"outDir": "./dist-esm",
"lib": ["dom"],
"resolveJsonModule": true,
"paths": {
"#azure/keyvault-secrets": ["./src/index"]
}
},
"include": [
"./src/**/*.ts",
"./test/**/*.ts",
"../keyvault-common/**/*.ts",
"samples-dev/**/*.ts"
]
}
You can refer to Where can I find tsconfig.json file in my react native project, tsconfig.json and Cannot find name 'URL'

import "!babel-loader!mdx-loader!foo.mdx" not working with react-scripts#5.0.0

Trying to upgrade an existing React project from react-scripts#4 to #5.0.0 fails for importing transpiled MDX sources.
/* eslint import/no-webpack-loader-syntax: off */
import AboutMDX from "!babel-loader!mdx-loader!./About.mdx"
AboutMDX does not receive an MDXComponent but instead now as of react-scripts 5 end up with a string which is the path name of the transpiled javascript source code file. How can I fix this change in behavior to correctly import the MDXComponent?
This has been an od(d)ysee because the whole MDX2+CRA5+remark/rehype ecosystem is prone to breakage in my experience. While MDX documents to use CRACO7 with CRA5, the MDX project when kindly asked points fingers to CRACO and wasn't helpful to me in getting me over ES modules and CSJ hurdles in order to finally get the pieces to work. While the following now works for me (at the moment) I don't know how robust this set up actually is.
upgrade to CRA 5
install CRACO 5
make sure to call the craco command instead of react in your package.json scripts.
make sure to clean up your (stale) dependencies.
add these dependencies and dev dependencies:
"#mdx-js/loader": "^2.2.1",
"#mdx-js/mdx": "^2.2.1",
"#mdx-js/react": "^2.2.1",
"#types/mdx": "^2.0.3",
"#craco/craco": "^7.0.0",
"#craco/types": "^7.0.0",
if in the past you had a declare module '*.mdx {...}' in a src/index.d.ts then remove this now completely, as it would conflict with what comes with the MDXv2 loader.
remove !babel-loader!mdx-loader! from all your *.mdx imports. Do not use !#mdx-js/loader! etc. either, as the webpack configuration below will take care of the preprocessing.
create a craco.config.js as follows; this is a more elaborate configuration that shows how to actually pull in ES modules with CRACO 5 still not supporting ESM in their configuration, but requiring to go through the dynamic import with delayed configuration setup hurdles:
const { addAfterLoader, loaderByName } = require('#craco/craco')
module.exports = async (env) => {
const remarkGfm = (await import('remark-gfm')).default
const remarkImages = (await import('remark-images')).default
const remarkTextr = (await import('remark-textr')).default
const rehypeSlug = (await import('rehype-slug')).default
const textrTypoApos = (await import('typographic-apostrophes')).default
const textrTypoQuotes = (await import('typographic-quotes')).default
const textrTypoPossPluralsApos = (await import('typographic-apostrophes-for-possessive-plurals')).default
const textrTypoEllipses = (await import('typographic-ellipses')).default
const textrTypoEmDashes = (await import('typographic-em-dashes')).default
const textrTypoEnDashes = (await import('typographic-en-dashes')).default
return {
webpack: {
configure: (webpackConfig) => {
addAfterLoader(webpackConfig, loaderByName('babel-loader'), {
test: /\.(md|mdx)$/,
loader: require.resolve('#mdx-js/loader'),
/** #type {import('#mdx-js/loader').Options} */
options: {
remarkPlugins: [
remarkGfm,
remarkImages,
[remarkTextr, {
plugins: [
textrTypoApos,
textrTypoQuotes,
textrTypoPossPluralsApos,
textrTypoEllipses,
// textrTypoEmDashes,
textrTypoEnDashes,
],
options: {
locale: 'en-us'
}
}],
],
rehypePlugins: [
rehypeSlug,
],
}
})
return webpackConfig
}
}
}
}

Customize Ant design with Next.js

I am using ant design in my next.js project. but I want to customize it, for example: " #primary-color: orange; "
I searched the internet and installed all the necessary npm packages, but since I have no webpack knowledge, I got different errors every time I tried. I tried many different codes in next.config.js but I got different errors for all of them. Can someone please explain to me how to do this?
here my folder tree :
and here my next.config.js file :
I would like to state in advance that I do not know anything about webpack.
const withSass = require("#zeit/next-sass");
const withLess = require("#zeit/next-less");
const withCSS = require("#zeit/next-css");
const isProd = process.env.NODE_ENV === "production";
// fix: prevents error when .less files are required by node
if (typeof require !== "undefined") {
require.extensions[".less"] = (file) => {};
}
module.exports = withCSS({
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: "[local]___[hash:base64:5]",
},
...withLess(
withSass({
lessLoaderOptions: {
javascriptEnabled: true,
},
})
),
});
and here my error :
yarn run v1.22.17
warning ../../../package.json: No license field
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
Warning: Built-in CSS support is being disabled due to custom CSS configuration being detected.
See here for more info: https://nextjs.org/docs/messages/built-in-css-disabled
TypeError: Cannot set properties of undefined (setting 'styles')
at module.exports (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/#zeit/next-css/css-loader-config.js:25:56)
at Object.webpack (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/#zeit/next-css/index.js:15:36)
at Object.getBaseWebpackConfig [as default] (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/build/webpack-config.js:1379:32)
at async Promise.all (index 0)
at async Span.traceAsyncFn (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/trace/trace.js:74:20)
at async Span.traceAsyncFn (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/trace/trace.js:74:20)
at async HotReloader.start (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/server/dev/hot-reloader.js:325:25)
at async DevServer.prepare (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/server/dev/next-dev-server.js:290:9)
at async /Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/cli/next-dev.js:128:9
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
➜ bakucosy-app git:(master) ✗

Resources