1

I am building an npm package.

When a user is using my package, I wish to for them to import the packages with the "@" like this:

import { Package } from "@initial/package"

I added this to my tsconfig.json:

    "baseUrl": ".",
    "paths": {
      "@": ["src"],
      "@/*": ["src/*"],
      "@initial": ["src/components"]
    }

but when I do an import:

import { Package } from "@initial/package";

It's throwing this error: Cannot find module '@initial' or its corresponding type declarations.

I have my src and tsconfig.json in the root.

webber
  • 595
  • 3
  • 10
  • 20
  • 1
    Does this answer your question? [How to make an import shortcut/alias in create-react-app?](https://stackoverflow.com/questions/63067555/how-to-make-an-import-shortcut-alias-in-create-react-app) – hisam Oct 24 '21 at 01:24
  • seems that recommendation is to use the library craco – webber Oct 24 '21 at 01:48
  • If you want consumers of your package to import your package with the `@` then add the `@` to your package's name. – juliomalves Oct 24 '21 at 15:39

1 Answers1

1

You can do that by changing the name for the project to start with @ in npm to can use it directly without aliases or any external library.

For example:

in packeage.json: "name": "@initial/package" and this is must be reflect to npm package:

for example:

https://www.npmjs.com/package/@initial/package

Note: You can use phantomChildren if you need to keep your module as is but you need to separate a specific package to build your own dependency: for example:

  "_phantomChildren": {
    "@initial/package": "....",
  },
Anees Hikmat Abu Hmiad
  • 3,460
  • 2
  • 19
  • 36
  • I actually also want to import the packages the same way within the project. Any suggestion for this? – webber Oct 24 '21 at 01:50
  • I think for other packages you need to follow its guideline or Alias all modules via webpack aliases (I'm not do that before for all modules, just for local paths alias), but if you want to do that for your npm module, you can do that by naming packages like above suggtion. I'm work on project now, and I use `addWebpackAlias` from `customize-cra` and then I alias needed path like this: ` addWebpackAlias({ "@kaitComponents": path.resolve(__dirname, "./src/components"), "@kaitApi": path.resolve(__dirname, "./src/api"), })` – Anees Hikmat Abu Hmiad Oct 24 '21 at 23:33