Search code examples
javascriptreactjsdependenciespackage.jsones6-modules

How to add local file dependency to package.json


I'm trying to add a local dependency to my package.json due to requiring to import an es6 module that is outsite of the react application /src directory.

My file directory structure is as follows:

https://ibb.co/wSGS2zc

-react_app_1/ (reactjs app)

-react_app_2/ (reactjs app)

-server.js

-ports.js

Where I need to import ports.js into both react applications.

In my package.json in both my 2 react apps, I have added the following:

"dependencies": {
    "server-ports": "file:../../ports"
}

However I recieve the following error when trying to serve the applications.

[1] node:internal/modules/cjs/loader:936
[1]   throw err;
[1]   ^
[1]
[1] Error: Cannot find module 'react-dev-utils/getPublicUrlOrPath'
[1] Require stack:
[1] - /Users/ivyjack/Sites/hcl-fos-app/master/config/paths.js
[1] - /Users/ivyjack/Sites/hcl-fos-app/master/config/env.js
[1] - /Users/ivyjack/Sites/hcl-fos-app/master/scripts/start.js
[1]     at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
[1]     at Function.Module._load (node:internal/modules/cjs/loader:778:27)
[1]     at Module.require (node:internal/modules/cjs/loader:999:19)
[1]     at require (node:internal/modules/cjs/helpers:102:18)
[1]     at Object.<anonymous> (/Users/ivyjack/Sites/hcl-fos-app/master/config/paths.js:5:28)
[1]     at Module._compile (node:internal/modules/cjs/loader:1099:14)
[1]     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
[1]     at Module.load (node:internal/modules/cjs/loader:975:32)
[1]     at Function.Module._load (node:internal/modules/cjs/loader:822:12)
[1]     at Module.require (node:internal/modules/cjs/loader:999:19) {
[1]   code: 'MODULE_NOT_FOUND',
[1]   requireStack: [
[1]     '/Users/ivyjack/Sites/hcl-fos-app/master/config/paths.js',
[1]     '/Users/ivyjack/Sites/hcl-fos-app/master/config/env.js',
[1]     '/Users/ivyjack/Sites/hcl-fos-app/master/scripts/start.js'
[1]   ]
[1] }

How I can I correctly source the dependency and how can I then import it within my react application?


Solution

  • Create a separate .json file to keep these data, include in your application, and me the file path in your .gitignore file.

    or Use dotenv package of NPM to store and import in your backend application.

    Use environment variables to store and read in your application.

    The above-mentioned are some good practices while including sensitive/unexposed data in the application.