Home > Net >  NPM. Paths for importing files from a package
NPM. Paths for importing files from a package

Time:12-31

Is it possible to customize the paths for importing files from a package?

I have a package, this is a UI kit for our internal project. Now after building the webpack I have the following project structure:

- dist
  - components
  - index.d.ts
  - index.js

before build by webpack index.ts looks something like this:

import { Button } from './components/Button';
...
import { Input } from './components/Input';

export { Button, ..., Input };

Now if I import the component like this:

import { Button } from '@package/name';

everything works and I get the desired result. But, I would like to slightly change the paths for convenience.

Is there a way to make it so that I can get the component from a specific path? Let's say like this:

import { Button } from '@package/name/base';
import { AccountIcon } from '@package/name/icons';

If I just change the structure of the dist folder, it will give me the ability to get the components, but the path will look like this (this is a working option):

import { AccountIcon } from '@package/name/dist/icons';

Is it possible to get rid of "dist" in the path and what is the best way to do it? Perhaps there are some materials that can be read? Didn't find anything about it.

I tried to change package.json, create a structure inside dist folder, changed the webpack config a little, but it was more like an attempt to find workarounds, I did not get the desired result.

CodePudding user response:

I'm not sure what exactly you want to achieve but, If you want to change the path for importing specific components, you can use the exports field in the package.json file. The exports field allows you to specify a mapping of individual exports to their corresponding file paths.

you can set the exports field like this:

"exports": {
  "./base": "./dist/base/index.js",
  "./icons": "./dist/icons/index.js"
}

Usage

import { Button } from '@package/name/base';
import { AccountIcon } from '@package/name/icons';

update

Is it possible to get rid of "dist" in the path and what is the best way to do it?

you can change the entry point of your package from the main field inside the package.json and you can point it to any path.

  • Related