webber
webber

Reputation: 775

How to import packages with @ in React?

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.

Upvotes: 1

Views: 3205

Answers (1)

Anees Hikmat Abu Hmiad
Anees Hikmat Abu Hmiad

Reputation: 3560

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": "....",
  },

Upvotes: 1

Related Questions