Cannot find module “fs”. Using simple-json-loader

2019-06-02 05:26发布

问题:

I'm try to use simple-json-loader. I install this from npm and write following function:

onclickExport() {
    var loader = require('simple-json-loader');
    var json = loader.JSONLoader.loadFromFile('wwwroot/dist/data/files.json');
}

Еverything seems simple, but when I run build in webback i see following error:

ERROR in ./~/simple-json-loader/index.js Module not found: Error: Cannot resolve module 'fs' in D:\GitRepo\Magazine\Magazine.Web\node_modules\simple-json-loader @ ./~/simple-json-loader/index.js

Npm package is in the node_modules by valid path. I see it there. Also In debugging of this function i see analogous error. Is any ideas why it is not work?

回答1:

You need to specify target in webpack config:

target: 'node'

And this will work only on server side as node.js program.



回答2:

It sounds like the issue is that the module simple-json-loader is reliant on the built-in Node module fs. fs is a module that performs various file-loading and file system tasks.

Since it looks like you're building in Angular2, which is a front-end (client-side) Javascript framework, this may be an environment issue.

It's not possible for the client-side browser environment to interpret and run some Node modules like fs that are built to be run in a server-side Node environment. (more here)

The solution is to run the simple-json-loader module server-side in a Node environment or to find a package which offers the same functionality but written for the browser.

It's discussed in this question... Module not found: Error: Cannot resolve module 'fs'

And this question... Use fs module in React.js,node.js, webpack, babel,express