Import from subfolder of npm package

后端 未结 5 1030
耶瑟儿~
耶瑟儿~ 2020-12-29 05:08

I\'ve been working on creating a small library of React components for use in several other projects. I am publishing the package internally (using a private GitHub reposito

5条回答
  •  不思量自难忘°
    2020-12-29 05:28

    Can I skip the src/ directory somehow in the import path?

    Yes. Using the package.json "exports" field, which should be supported by Webpack in a near future (see this issue), but has already been supported by Node since Node 12 LTS following the Bare Module Specifier Resolution proposal:

    package.json

    ...
    "main": "./src/index.js",
    "type": "module",
    ...
    "exports": {
      "./Button": "./src/Button/index.js",
      "./Header": "./src/Header/index.js"
    },
    ...
    

    Now, the following code:

    // This project is responsible for building/transpiling after importing
    import { Button, ButtonGroup } from 'components-library/Button';
    

    should be translated to:

    import { Button, ButtonGroup } from 'components-library/src/Button/index.js';
    

    which should correctly import the requested modules.

    Caveat

    Now, it would certainly be tempting to try a simpler version like:

    ...
    "exports": {
      "./Button": "./src/Button/",
      "./Header": "./src/Header/"
    },
    ...
    

    so as the usual import statement

    import { ... } from 'components-library/Button';
    

    gets translated to

    import { ... } from 'components-library/src/Button';
    

    This looks nice, but it will not work in this case, because your submodules don't have each their own package.json file but rely on their index.js file to be found.

    /!\ Unlike in CommonJS, there is no automatic searching for index.js or index.mjs or for file extensions.


    src/index.js - Is this file actually necessary if only importing from subdirectories?

    I don't think so, but you can keep it if you want.


    Can I skip any type of build phase in the package?

    Using the "exports" field does not require you to transpile your code.

提交回复
热议问题