4

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 using 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.

laurent
  • 88,262
  • 77
  • 290
  • 428
Vlad
  • 43
  • 2
  • I think this will help you get what you want https://webpack.js.org/guides/package-exports/ – NirG Dec 30 '22 at 11:52
  • @MartijnPieters, you deleted the answer to this question, but why? I looked for the answer to that question everywhere and only found it here... but deleted. I'm glad I can see deleted answers but still it's a strange. Can it be restored? – laurent Mar 21 '23 at 19:04

1 Answers1

2

You can use the export field from package.json to do this. For example:

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

Don't forget the "./" which is required.

(Note: this was based on someone else's answer that has now been deleted because it was generated by ChatGPT. I'm putting back the gist of it here because the answer was actually useful)

laurent
  • 88,262
  • 77
  • 290
  • 428