Home > OS >  Can't resolve error appears only in my webpack-build
Can't resolve error appears only in my webpack-build

Time:12-21

I'm trying to import a module _module_name_ into my current react-project with typescript, say react-app for reference. The project is bundled up with webpack. I'm importing it into one of my .tsx components. The module that I am importing was written by me and I published it on npm. I'm getting a cannot resolve error when building my react project. It cannot resolve the fs module, apparently. I wonder what causes this problem? Here is the error output:

ERROR in ./node_modules/_module_name_/index.js 2:11-24
Module not found: Error: Can't resolve 'fs' in 
'/path/to/project/node_modules/_module_name_'
resolve 'fs' in '/path/to/project/node_modules/_module_name_'
   Parsed request is a module
   using description file: /path/to/project/node_modules/_module_name_/package.json (relative path: .)
      Field 'browser' doesn't contain a valid alias configuration
      resolve as module

The _module_name_ is extremely simple. For all practical purposes it looks like this:

// index.js
const path = require('path')
const fs = require('fs');

function foo() {
    const abi = JSON.parse(fs.readFileSync('file.json', 'utf8'));
    return abi
}

module.exports = {
    foo
};

Then I have a typescript declaration file:

// index.d.ts
export function foo(): any;

Of course I have the file itself:

// file.json
{
    "a": 1
}

and I have a package.json in that _module_name_ which contains at least the following entries:

// package.json
{
    "main": "index.js",
    "types": "./index.d.ts",
    "dependencies": {
        "fs": "^0.0.1-security",
        ...
    }
    ...
}

Remark: When I am in my react project react-app I have no problems importing foo in any old javascript file or typescript file. It will work perfectly unless it's part of the react app. How strange is that. Maybe it has to do with my webpack loaders, cause I'm using webpack to bundle the app.

Question: Is the problem on the side of the _module_name_ or on the side of the react-app?

CodePudding user response:

just had a quick read, but basically you are trying to use nodeJS in the browser. that's not a good idea. have a look here: Can't resolve 'fs' using webpack and react requiring the files and then parsing should work

  • Related