Macilias
Macilias

Reputation: 3533

node: how to extend module.paths

I need to have access via require to my custom static files. Therefor I created a directory 'assets' and promoted it to package:

|-assets
|    |-default-asset.json
|    |-package.json

where package.json looks like this:

{
  "name": "assets",
  "version": "1.0.0",
  "main": "./default-asset.json"
}

I needed to set the "main" property to something existing within the packe to not become ignored by node. How ever, now the package is part of the node_modules library root.

But when I call node to check module.paths its still not listed:

(base) ➜  server git:(master) ✗ node
Welcome to Node.js v12.13.1.
Type ".help" for more information.
> module.paths
[
  '/.../server/repl/node_modules',
  '/.../server/node_modules',
  '/.../node_modules',
  '/user/node_modules',
  '/home/node_modules',
  '/node_modules',
  '/home/user/.node_modules',
  '/home/user/.node_libraries',
  '/usr/lib/node'
]
> 

That's probably a problem, because when trying to require one of the files from within the folder I still have got the exception:

internal/modules/cjs/loader.js:800
    throw err;
    ^

Error: Cannot find module './assets/default-asset.json'
Require stack:
...

Upvotes: 1

Views: 711

Answers (1)

Macilias
Macilias

Reputation: 3533

YES, i finally managed to fix it, and for any other persons who struggles with it here is how:

  1. The custom package need to be referenced from the app/package.json and
  2. even more importantly, from package-lock.json with "version": "file:custom-assets" annotation!
  3. The package.json must contain a "main" entry which references one of the files inside and its path must start with ./!!!
  4. The usage of the asset must NOT start with ./ but /!!!

Now the path is there:

$ node 
> module.paths
[
  '.../important-code-snippets/JavaScript/require-custom-assets/repl/node_modules',
  '.../important-code-snippets/JavaScript/require-custom-assets/node_modules',

Here is also a full running example: https://github.com/Macilias/important-code-snippets/tree/master/JavaScript/require-custom-assets

Upvotes: 2

Related Questions