How to refer my package.json from /dist/app.js

1.2k views Asked by At

For my web application, when I try to import a version tag from package.json to app.js (/src/app.js), which is one level up to app.js, the local run works fine. But when I try to run from development by generating a dist folder, the code does not work even though both src and dist folder are at same level and should be able to access package.json.

When I deploy to development, I get error as follows:

Error: Cannot find module '../package.json'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)

Can someone pls help me with this?

1

There are 1 answers

1
Stephane Janicaud On

If you're using Node.js, which seems to be the case, use node native path module to resolve package.json path. Here is an example :

src/
  path/
    to/
      subdir/
        foo.js
index.js
package.json

package.json

{
  "version": "1.0"
}

foo.js

const path = require('path');
const packageJson = require(path.resolve('package.json'));

module.exports = {
  "packageVersion": packageJson.version
}

index.js

const path = require('path');
const packageJson = require(path.resolve('package.json'));
const foo = require('./src/path/to/subdir/foo');

console.log(packageJson.version);
console.log(foo.packageVersion);

When your run node index, you'll get the following output

1.0
1.0

The version from package.json is read from both index.js and foo.js using path.resolve('package.json')