0

I want to avoid using relative paths, and I found this proposed solution, where you specify a @local/package/name pointed at file:path/to/file. I did not want to use Babel or something similar to address this issue, and so this seemed like a solid solution. I also found that they advertise this functionality in the docs.

So ideally, instead of:

const FAClientManager = require("../../api/manager");

I can use, anywhere in my project:

const FAClientManager = require("@local/api/manager");

In my package.json, I set:

    "dependencies": {
        "@local/api/manager": "file:./api/manager",

However, npm v8 is throwing this error when I try to use that package name:

npm ERR! code EINVALIDPACKAGENAME npm ERR! Invalid package name "@local/api/manager" of package "@local/api/manager@file:./api/manager": name can only contain URL-friendly characters.

If I change the package name from @local/api/manager to local/api/manager, the same issue occurs. However if I also remove the slashes and make it apimanager, then it works. I don't want to use apimanager though, and I'd like to use the slashes for readability. I am importing other packages such as @keyv/postgres without issue, so why is it rejecting this file-based package?

The issue appears to occur if there's more than one slash, i.e. @local/test is good, but @local/test/second throws the error.

gwizzo
  • 41
  • 7

1 Answers1

0

As per https://github.com/npm/npm/issues/6333, you cannot nest that deep. So @local/package is your limit, and @local/package/something would throw the error being seen.

If you wanted to set a root path for reference throughout your project, you would add:

    "dependencies": {
        "@local/self": "file:./",

And throughout your project, you could use at any level, for example:

require("@local/self/config.json");

Or for a module in a folder in your app directory, you could use at any level:

require("@local/self/some-module/path/module.js");
// or, of course:
// require("@local/self/some-module/path/module");

That way, instead of dealing with the ../../ relative imports and worrying when you move files around, you can just do a search and replace for @local/self/some-module/path/module with @local/self/some-module/new/path/module.

gwizzo
  • 41
  • 7