Do you want to request a feature or report a bug?
Bug
What is the current behavior?
Webpack finish bundle without errors with css-loader 0.26.4.
After update to 0.27.0 webpacking finished with error:
ERROR in ./~/convert-source-map/index.js
Module not found: Error: Can't resolve 'fs' in 'C:\Projects\project_name\node_modules\convert-source-map'
@ ./~/convert-source-map/index.js 2:9-22
@ ./~/css-loader/lib/css-base.js
If the current behavior is a bug, please provide the steps to reproduce.
0.26.4 to 0.27.0 versionWhat is the expected behavior?
Works without error
Please mention other relevant information such as your webpack version, Node.js version and Operating System.
Windows 8.1
Node.js 7.7.2
Webpack 2.2.1
same here
same here
Same for me, had to rollback that update
same here
Adding
node: {
fs: 'empty'
}
to webpack config file and the error is gone. Not sure how it works, It seems like webpack did some thing with fs module in web target.
add the following to your Webpack config:
node: {
fs: "empty"
}
The issue has been acknowledged and we are in process of figuring out a good fix. No need for "me too"s. Please add a thumbs up on the original issue if you want to do that. 👍
Did you can to unpublish this version? It will keep calm to all of us
@PredokMiF You don't unpublish anything, ever.
The workaround is sufficient and the bug is actually in webpack, related to fs in the web target.
WORKAROUND thanks to @hdnha11 / @mehdivk
node: {
fs: 'empty'
}
If using this workaround isn't viable, version lock to the previous minor version.
@bebraw With your fix of this issue, I have a Uncaught ReferenceError: Buffer is not defined in the lib/convert-source-map.js file, in the browser.
@fklingler I have a proposed fix for that at https://github.com/webpack-contrib/css-loader/pull/453 . Still waiting for some approvals before I can push it. Feel free to give that a go and let me know how it goes.
I came across the same error. I am starting off with JS (with vuejs) and I would like to understand what this does?
I got this error when using the "fetch" library from npm. At first I got the same error but with other packages (net and dns). My first thought was that those are missing dependencies. After running npm install net and npm install dns, those errors were replaced with dgram and fs. The latter one prompted me to hit Google and landed on this issue.
I now added two sections in my webpack config for both fs and dgram, and now the errors are gone.
But I don't know what this entails. Will my compiled code still work? Even if these sections are configured as being empty? What does it actually do?
Also, is this the right place to ask this? Or should it be rather targeted at vuejs?
nb: I would like to give a bit more insight about my running environment but as I'm still getting my feet wet, I don't know which commands are the best to represent a snapshot of my dev-environment. If you need some additional output, let me know which commands to run.
@exhuma See the related page on documentation. That describes the default behavior. You can also find possible overrides there. I hope this helps.
Also, is this the right place to ask this? Or should it be rather targeted at vuejs?
Stack Overflow might be better for this type of questions.
just wanted to add that I fixed this by the answer in https://github.com/josephsavona/valuable/issues/9 about setting target: 'node'
This explains more: http://jlongster.com/Backend-Apps-with-Webpack--Part-I
The target: 'node' option tells webpack not to touch any built-in modules like fs or path.
Hi - when I did
target: 'node',
the error went away. Then I got
global not defined,
so I fixed it with
'global': {}, in webpack.definePlugin({...})
Then I got a GetEnv error saying SERVER_HOST not defined... but it is... so there's a slew of errors that I'm swimming in - I hope someone can take a look at my boilerplate and give me hand? Thank you!
I fixed the problem by changing webpack.config.js:
...
var config = Encore.getWebpackConfig();
config.node = { fs: 'empty' };
module.exports = config;
and:
yarn add --dev file system
Someone please fix this issue. Non of the mentioned answer could fix it for me
@samayo I'm not sure what I got could help you.
I fix this error by installing node-sass into devDenpendency, if I install node-sass into denpendency, I will get this error, I'm not sure you use node-sass or not, you can check some packages in denpendency and devDenpendency
How should I go about solving this issue when importing an npm module that uses Webpack (i.e., when importing an npm module that imports a package that yields this problem)?
To add some clarity: say I've create two npm modules, both using Webpack. Let's call them module A and module B.
Module A imports require, which yields this error. Thus, in webpack.config.js of module A, I add:
node: {
console: false,
fs: 'empty',
net: 'empty',
tls: 'empty'
}
Module B then imports module A. However, even though I've added the above code in module A, the error still comes up when I try to build module B.
Does anyone know how to solve this problem without adding the above code to module B as well (i.e., modifying only module A)?
Same problem - why is this issue closed? Should I 👍 a different issue?
I got this problem because I ran: webpack webpack.config.js rather than webpack --config webpack.config.js. It bundled webpack itself and it took forever to bundle.
This bug is still occurring. Haven't it been fixed yet?
I had this issue when i unintentionally imported Session from selenium-webdriver as follow :
import {Session} from "selenium-webdriver";
I had this issue when webpacking my app along with urllib which depends on fs and child_process, and luckily both of these two dependencies have this issue! I almost gave up on the lib, but this thread saved my life. Looking forward to resolving this issue.
Error on fetch for node_modules/angular2-notifications/src/simple-notifications.module.js at file:///D:/GIP/IMAGE PILOT/gipfe/node_modules/angular2-notifications/src/simple-notifications.module.js Loading build/tmp/aot/src/app/app.module.ngfactory.js Loading build\boot-aot.js Error: ENOENT: no such file or directory, open 'D:\GIP\IMAGE PILOT\gipfe\node_modules\angular2-notifications\src\simple-notifications.module.js' [10:13:51] 'build.aot' errored after 52 s [10:13:51] Error in plugin 'run-sequence(bundle-aot)' Message: Error on fetch for node_modules/angular2-notifications/src/simple-notifications.module.js at file:///D:/GIP/IMAGE PILOT/gipfe/node_modules/angular2-notifications/src/simple-notifications.module.js Loading build/tmp/aot/src/app/app.module.ngfactory.js Loading build\boot-aot.js ENOENT: no such file or directory, open 'D:\GIP\IMAGE PILOT\gipfe\node_modules\angular2-notifications\src\simple-notifications.module.js' Details: originalErr: Error: ENOENT: no such file or directory, open 'D:\GIP\IMAGE PILOT\gipfe\node_modules\angular2-notifications\src\simple-notifications.module.js' Stack: Error on fetch for node_modules/angular2-notifications/src/simple-notifications.module.js at file:///D:/GIP/IMAGE PILOT/gipfe/node_modules/angular2-notifications/src/simple-notifications.module.js Loading build/tmp/aot/src/app/app.module.ngfactory.js Loading build\boot-aot.js Error: ENOENT: no such file or directory, open 'D:\GIP\IMAGE PILOT\gipfe\node_modules\angular2-notifications\src\simple-notifications.module.js'
build error is came after i update node modules using npm install command then, i try to take build using npm run build.aot command then above errors was came
pls help me to solve this.
The suggested answer does not work. Where is everyone even putting the fix node: {fs: "empty" } I have about. I have 4 webpack config files in /config/ and which line? I tried putting it everywhere but no solution ..
Before i installed typescript version
"typescript": "^2.3.3", // package.json
then i changed the typescript version
"typescript": "2.3.3", //without cap symbol
Now,error was not came and i took build successfully
@samayo try this
Thanks. But I get this error now
Uncaught File 'Roboto-Regular.ttf' not found in virtual file system
I don't know why this issue is ignored
@samayo can you provide link to this issue?
And all who have this bug (solution: fs: 'empty') please provide minimum reproducible test repo, thanks
I haven't created any issues for this yet. I just have the same issue as everyone else. There are certain libraries than when I install I get the same error as everyone else: Module not found: Error: Can't resolve 'fs' in last time I got that error I chose not to use the lib, and today I installed https://github.com/bpampuch/pdfmake/ and I got the error.
Can someone share where exactly you are passing fs: 'empty'?
@samayo
node: {
// eslint-disable-next-line camelcase
child_process: "empty",
dgram: "empty",
fs: "empty",
net: "empty",
tls: "empty"
},
@samayo you try to use library in browser which require fs or maybe other module(s) which inavailable in browser env. You should search fs polyfill or rewrite library to compatibility with browser env. OR maybe you load non browser library version.
@samayo I fixed the issue adding it to the karma.conf.js file. The file's content is now like this:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular/cli/plugins/karma')
],
files: [
{ pattern: './config.json', watched: false }
],
exclude: [
'./config.json'
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
angularCli: {
config: './angular-cli.json',
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
webpack: {
node: {
fs: "empty"
}
}
});
};
As you can see, at the end of the file, I added a new webpack entry and inside it the mentioned solution.
@christianvuerings Thanks. This is what I was looking for, sadly I am not using Karma. And I am not sure how to pass this or where... but it probably wouldn't work because I tried putting it everywhere
Why is this issue closed? I just spent the last two days racking my brains, until I finally stumbled upon this bug report with a lucky combination of search keywords. The workaround seems like a really bad one. Will we see a fix?
I get an error like this:
TypeError: fs.readFileSync is not a function
@vgjenks @tjvg91 please read above. Need minimum reproducible test repo. Thanks!
Super annoying! None of the fixes work for me. And there's nothing to reproduce. just require("fs") causes the problem.
node: {
fs: 'empty'
}
The work-around allows us to run the webpack, but if our application needs to use FS for any reason, like write to file, the work-around is now a problem as FS no longer exists.
fs.writeFile is not a function
Does anyone have a different solution?
@Percapio add this
target: 'node'
@mrkaspa not only did your suggestion resolve my fs issue, I had other modules as well and it resolved all of them ('net' was one)
None of these suggestions have worked for my env. How is this not fixed?
npm install fs --save doesn't seem to have any affect in my case.
https://webpack.js.org/configuration/target/ hints I should be using target: 'web'.
This gives me _Can't resolve 'fs'_.
node: { fs: "empty", } gives me _fs2.default.readFileSync is not a function.
Changing to target: 'node' gives me require is not defined (people also mentioning this in comments here.
Oops, I've been trying to run a node module in the browser to do some validation.
Of course, the browser doesn't have file system access.
In the end I just ran build on the node module and import or require the /dist .js file
module.exports in my _webpack.config_ filenode: {
fs: 'empty'
},
There is a better solution available hee
Maybe it will help some of you.
I was having this issue because an emscripten built dependency was used by my project.
Emscripten js output contains require(‘fs’).
same here
If any of you is using NextJS to fix this problem, you can add:
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders }) => {
config.node = {
fs: 'empty'
}
return config
},
}
To your next.config.js file
@J-Gallo Thank you so much!
next.config.js
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders }) => {
config.node = {
fs: 'empty',
module: "empty",
};
return config;
},
};
I just had to add the module: "empty", as well.
For those of you using Nuxt.js for Vue.s server-side rendering, webpack can be extended as follows:
nuxt.config.js
module.exports = {
...
build: {
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
...
config.node = {
fs: 'empty'
}
}
}
}
}
However, if you need fs for any reason, you may run into the same issues as mentioned above and require further workarounds
I solved this by just requiring the fs module in my electron window:
const fs = window.require('fs');
Looks like something in ipcRenderer tries to use it without defining it? Once it was defined all my errors went away.
So is there proper fix for this? I'm not having any luck in React with these workarounds.
Similar situation: Node, Webpack, React. Trying to read a file using fs.readFileSync and am getting this error.
Per this discussion, looks like memfs is being considered for use as a browser replacement for Node's fs package.
From what I can tell, the main problem is accessing Node libs for browser use.
@justinstander Here's my settled-upon solution:
I keep a file one directory above my project that contains my relevant env vars in JSON format.
In my webpack.prod.config.js file, I perform the following code:
var fs = require('fs');
var config = JSON.parse(fs.readFileSync('../env-vars.env'));
module.exports = {
...
plugins: [
new webpack.DefinePlugin({
'USER_URL': JSON.stringify(config.userURL),
'DATA_URL': JSON.stringify(config.dataURL)
})
In my code, I use these vars like so:
export const CONFIG = {
...
userURL: USER_URL || 'https://localhost',
dataURL: DATA_URL || 'https://localhost'
};
This works for me in my environment. My sensitive data is kept in a file outside the project. Node gets to use fs to import that data, and WebPack gets to supply it in global vars. Those vars are not exposed on the window object.
I hope this helps you with your project!
@executives what if you want to access the fs library outside of webpack.config.js ?
Example:
File: configLoader.js
const fs = require('fs');
// Get content from file
const config = fs.readFileSync("./config/local/config.json");
const properties = JSON.parse(config);
console.log("Environment: " + properties.environment);
console.log("HomepageUrl: " + properties.homepageUrl);
File: webpack.config.js
"use strict";
const webpack = require('webpack');
const path = require('path');
module.exports = function(env) {
console.log('NODE_ENV: ', env.NODE_ENV); // 'local'
const CURRENT_ENV = 'local';
let NEW_ENV = 'local';
if (env.NODE_ENV === 'production') {
NEW_ENV = env.NODE_ENV;
}
return {
node: {
fs: 'empty'
},
entry: path.join(__dirname, "./", "configLoader.js"),
output: {
path: path.join(__dirname, "dist"),
filename: "bundle.js"
},
module: {
loaders: [
{
test: path.join(__dirname, "src"),
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}
]
},
plugins: [
new webpack.NormalModuleReplacementPlugin(/config\/local\/config\.json/, function(resource) {
resource.request = resource.request.replace(/config\/local\/config\.json/, `/config\/${NEW_ENV}\/config\.json`);
})
]
}
};
File: local/config.json
{
"environment": "local",
"homepageUrl": "http://localhost:8080"
}
File: production/config.json
{
"environment": "production",
"homepageUrl": "http://www.google.com"
}
I try and run node dist/bundle.js but I get the following error...
➜ 03_branching git:(master) ✗ node dist/bundle.js
/Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:73
const config = fs.readFileSync("./config/local/config.json");
^
TypeError: fs.readFileSync is not a function
at Object.<anonymous> (/Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:73:19)
at __webpack_require__ (/Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:20:30)
at /Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:63:18
at Object.<anonymous> (/Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:66:10)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
I works if I run
node configLoader.js
But if I run the webpack command:
webpack --env.NODE_ENV=production
node dist/bundle.js
It fails...
Anyone know what's going on?
I added node: { fs: 'empty' } without luck,
then I added --config to start command:
̀webpack-dev-sever webpack.config.dev.js`
You must add the --config flag to put in a custom file.
̀webpack-dev-sever --config webpack.config.dev.js`
Boom! It worked.
after adding {fs: 'empty'} I get this:
external_"url":1 Uncaught ReferenceError: require is not defined
at eval (external_"url":1)
at Object.url (bundle.js:1065)
at __webpack_require__ (bundle.js:683)
at fn (bundle.js:60)
at Object.eval (webpack:///(:8080/webpack)-dev-server/client?:6:11)
at eval (webpack:///(:8080/webpack)-dev-server/client?:249:30)
at Object../node_modules/webpack-dev-server/client/index.js?http://0.0.0.0:8080 (bundle.js:763)
at __webpack_require__ (bundle.js:683)
at fn (bundle.js:60)
at eval (webpack:///multi_(:8080/webpack)-dev-server/client?:1:1)
Still i am unable to resolve the fs error plz help me
mee too
I have the problem too, and until now I approximately have looked up all issues related to the problem, but can't fix it.
my problem is exactly:
I'm working on an angular-universal project.
after I added dom-storage to my project, I got the can't resolve fs error in (browser) build process, and the main provied solution is adding fs: 'empty' to webpack.config.js. but I tried all solutions and couldn't fix it.
after a lot, now I think the problem can be from here :
I bring up my thought. It would be appreciated if help me to know the solution.
at first, we know angular-cli uses webpack to do build angular projects (according to the documentation).
and I think there is no any config file for webpack in this process, and webpack.config.js is only used for bundling server.ts file in our project. so every change in webpack.config.js file can't impresses on build process in my project. now my questions are:
I have a working solution for webpack to transfer any variables in the front-end, if it can help someone.
In your webpack.config.client.js before anything else:
require('dotenv').config()
const webpack = require('webpack')
In your webpack.config.client.js in the plugins section just redefine anything you want in the front-end:
new webpack.DefinePlugin({
'process.env.MY_VAR': process.env.MY_VAR,
'process.env.MY_OTHER_VAR': process.env.MY_OTHER_VAR,
'process.env.MY_STRING': '"' + process.env.MY_STRING + '"',
}),
And that's all, now you can access process.env.MY_VAR from anywhere in the front-end and you don't need to call the dotenv in your front-end.
I have a React SSR (server side rendering) website, and both my server.js and browser.js go through webpack. For this purpose I have:
webpack.server.js:
{
target: 'node',
}
webpack.browser.js:
{
node: {
fs: 'empty',
}
}
This way my server.js can actually fs.write, and the browser only gets rid of compile errors.
The solution for me was to hack the Angular-CLI module to spoof the missing node modules.
After installing locate the following file:
node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/browser.js
Find the node line and add this:
node: { crypto: true, stream: true, fs: 'empty', net: 'empty' }
And that's it!!!
Note: You will need to do this patch every time you update the package. So use this script:
package.json
"scripts": {
...
"postinstall": "node patch-webpack.js"
...
}
patch-webpack.js
const fs = require('fs');
const f = 'node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/browser.js';
fs.readFile(f, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
let result = data.replace(/node: false/g, "node: {crypto: true, stream: true, fs: 'empty', net: 'empty'}");
fs.writeFile(f, result, 'utf8', function (err) {
if (err) return console.log(err);
});
});
I don't know about you guys. But I fixed the issue by restarting the computers. So the conclusion is drawn. It is a bug.
node: {
fs: 'empty'
}
Does not work for me.
I'm having the same issue, I don't know where I have to write the
node: {
fs: 'empty'
}
resolve: {
modules: ['app', 'node_modules'],
extensions: [
'.js',
'.jsx',
'.react.js',
],
mainFields: [
'browser',
'jsnext:main',
'main',
],
},
node: { fs: 'empty' },
devtool: options.devtool,
target: 'web', // Make web variables accessible to webpack, e.g. window
performance: options.performance || {},
});
Could someone respond with an explicit file path (ex. node_modules/webpack/package.json) for where I need to add node: { fs: 'empty' }, and also include the entire file? I can't find this magical webpack config file everyone is raving about. I have been struggling for a number of hours trying to get file-system to work and have tried adding node: { fs: 'empty' } to a number of places but it doesn't work.
I'm working in angular 8.0.1
Also, if anyone knows a working alternative to file-system, let me know.
Thanks
Please don't use old css-loader version, update to latest (no problems with fs)
Thanks for the quick response but I just updated css-loader and still have the same error.
package.json:
{
"name": "web-client",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng build --prod --aot --configuration=production",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^8.0.0",
"@angular/cdk": "^7.3.7",
"@angular/common": "^8.0.0",
"@angular/compiler": "^8.0.0",
"@angular/core": "^8.0.0",
"@angular/forms": "^8.0.0",
"@angular/platform-browser": "^8.0.0",
"@angular/platform-browser-dynamic": "^8.0.0",
"@angular/router": "^8.0.0",
"@fullcalendar/core": "^4.2.0",
"@fullcalendar/daygrid": "^4.2.0",
"@fullcalendar/interaction": "^4.2.0",
"@fullcalendar/timegrid": "^4.2.0",
"@ng-select/ng-select": "^2.20.0",
"@ngtools/webpack": "^8.0.1",
"@ngx-pwa/local-storage": "^8.0.0",
"ajv": "^6.10.0",
"core-js": "^3.1.3",
"css-loader": "^3.1.0",
"docxtemplater": "^3.14.0",
"file-system": "^2.2.2",
"jszip": "^3.2.2",
"jwt-decode": "^2.2.0",
"moment": "^2.24.0",
"path": "^0.12.7",
"primeflex": "^1.0.0-rc.1",
"primeicons": "^1.0.0",
"primeng": "^8.0.0-rc.1",
"rxjs": "^6.5.2",
"stream": "0.0.2",
"zone": "^0.3.4",
"zone.js": "^0.9.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.800.1",
"@angular/cli": "^8.0.1",
"@angular/compiler-cli": "^8.0.0",
"@angular/language-service": "~8.0.0",
"@types/jasmine": "~3.3.13",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^12.0.12",
"codelyzer": "^5.1.0",
"jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "^4.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.2",
"protractor": "~5.4.0",
"ts-node": "~8.2.0",
"tslint": "~5.17.0",
"typescript": "^3.4.5"
}
}
Error:
ERROR in ./node_modules/file-system/file-system.js
Module not found: Error: Can't resolve 'fs' in 'C:project\node_modules\file-system'
Please provide minimum reproducible test repo
This dependency was not found:
* fs in ./node_modules/fs-extra/lib/index.js, ./node_modules/fs-extra/lib/empty/index.js and 2 others
To install it, you can run: npm install --save fs
wait for me to give a test repo
In case, if your target is node in webpack (target: 'node'), because you want to fix "Can't resolve 'fs'. Then you're getting the following error Fix: "Uncaught ReferenceError: global is not defined" do it as follows node: { global: true, fs: 'empty' }. Bonus: if you got error "Uncaught ReferenceError: exports is not defined". simply add libraryTarget: 'umd'. The complete webpack config code is below.
const webpackConfig = {
node: { global: true, fs: 'empty' }, // Fix: "Uncaught ReferenceError: global is not defined", and "Can't resolve 'fs'".
output: {
libraryTarget: 'umd' // Fix: "Uncaught ReferenceError: exports is not defined".
}
};
module.exports = webpackConfig; // Export all custom Webpack configs.
Me Too. This is still an issue
I came across this issue and figured that it is because I was setting cucumber timeout in an Angular app inside a file under src/app. Moved the setting into a file under e2e folder and the error is gone.
Modify webpack.config.js:
var path = require('path');
module.exports = {
entry: './src/main.js',
target: 'node',
output: {
path: path.join(__dirname, 'build'),
filename: 'backend.js'
}
}
Refer here
Thanks for Helpful 🥇
Came across this issue while playing with worker-loader, but the related issues in worker-loader are all marked as fixed. I just tried adding the node: { fs: 'empty' } trick, but also had to add module: 'empty' to it to get that to work.
This seems to work, but has caused a four-fold increase in bundle size for the browser :O zero increase in the same module built for node.
For those using preact (which uses webpack), borrowing from Eric’s version above, I had to add the following into the preact.config.js file to make it disappear:
```js
export default (config, env, helpers) => {
config.node.fs = 'empty'
}
For me what caused this was installing dotenv-webpack and then uninstalling it without removing the lines that reference it like imports. Hope this helps someone. Setting both node: { fs: 'empty'} and target: 'node' helped me find the the problem.
I've been having this issue.
ERROR in C:/Users/gunsl/IdeaProjects/FL/build/js/node_modules/node-gyp-build/index.js
Module not found: Error: Can't resolve 'fs' in 'C:\Users\gunsl\IdeaProjects\FL\build\js\node_modules\node-gyp-build'
@ C:/Users/gunsl/IdeaProjects/FL/build/js/node_modules/node-gyp-build/index.js 1:9-22
@ C:/Users/gunsl/IdeaProjects/FL/build/js/node_modules/utf-8-validate/index.js
@ C:/Users/gunsl/IdeaProjects/FL/build/js/node_modules/ws/lib/Validation.js
@ C:/Users/gunsl/IdeaProjects/FL/build/js/node_modules/ws/lib/Receiver.js
@ C:/Users/gunsl/IdeaProjects/FL/build/js/node_modules/ws/index.js
@ ./kotlin-dce/ktor-ktor-client-core.js
@ ./kotlin-dce/FL-frontend.js
@ multi ./kotlin-dce/FL-frontend.js
When I go into node-gyp-build and end the index.exe to remove the first line var fs = require('fs') and rerun it this time ensuring the gradle task "npmInstall" doesn't run... when I do that this thing seems to start up ok.
Note I see this other module in node called fs.realpath and also fs.extra and potentially one more... fs.realpath source sounds like a clue, but the read me's aren't that telling. The npm repo online says fs is obsolete so why does node-gyp-build, whatever it, ignore it or update it... I can't go in here and remove that line everytime I install.
The webpack config solution discussed here sounds great however that gets generated by gradle so I don't want to have to edit that manually either, lol, and can't figure out how to make gradle do it either... stuck.
but I do not use webpack, how can I resolve this problem
I solved all these issues the other day, dont recall exactly how but if I recall correctly it was just a misconception of mine while learning node... I was point script tags to the node_modules folder... but I dont think that's how node works. Switched to static files for now... long term I think your really supposed to use node to download and compile from the sources to avoid statics and maintain compile options... is my understanding.
So, this is for webpack 4 users. Maybe it might help others who bump into this thread. There is a configuration param called target. So this resolves the 'fs' error in webpack
When i use fs as empty , there is no way for the bundled code to know /access fs modules of nodejs and that becomes a problem when we use it elsewhere in the code. So atleast I definitely do not recommend the fs:empty usage as suggested above
module.exports = {
entry: './src/index.ts',
mode: 'production',
**target: 'node',**
module: {
rules: [
{
test: /\.ts$/,
use: [
'ts-loader',
],
exclude: /node_modules/,
},
]
},
....
..
};
And here is my tsconfig. The module config is set to commonjs and target to es2015
{```
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2015",
"noErrorTruncation": true,
"allowJs": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"lib": ["ES2015", "ES2016", "ES2018", "ES2019", "ES2020", "ESNext"],
"sourceMap": true,
"rootDir": "./src",
"outDir": "./dist",
"baseUrl": "./",
"declarationMap": true,
},
"include": ["src/*/.ts"],
"exclude": ["node_modules", "dist", "test"],
"compileOnSave": true
}
```
Seems many issues like this can be solved with tool configs like the previous post; there are so many things like that which need to be configured, yet as far as I can tell grade doesn't provide the means to do it and since web pack config get generated automatically, It can't be edited directly. Really surprised the gradle people only exposed like 2 web pack config properties, at least in the multiplatform setup anyways.
@vijayakumar-psg587 so the fix for you was this
The module config is set to commonjs and target to es2015
?
For Webpack >5 You shoud add a block to webpack.config.js like this:
//webpack.config.js
module.exports = {
...
resolve: {
fallback: {
"fs": false
},
}
}
For me (webpack with electron) the problem was apparently that I was doing require('fs/promises') but changing it to require('fs').promises seems to have fixed it.
@majidgh72
Your solution lets webpack bundle the code successfully but when I run the app I get error
Uncaught reference Error: process is not defined
Thanks @majidgh72, the migration to webpack 5 talks about fs as a fallback.
@Powersource Should be work without any problems on v5 https://github.com/webpack/webpack/blob/0c4d47a987f3688c663c7a7e18fe8e277e6f98c8/lib/node/NodeTargetPlugin.js#L27
Got this error.
[webpack-cli] Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
- configuration.node has an unknown property 'fs'. These properties are valid:
object { __dirname?, __filename?, global? }
-> Options object for node compatibility features.
on Doing
config = Encore.getWebpackConfig();
config.node = { fs: "empty" };
module.exports = config;
Most helpful comment
Adding
to webpack config file and the error is gone. Not sure how it works, It seems like webpack did some thing with
fsmodule inwebtarget.