Search code examples
reactjsnpmreact-spinners

Allow direct import of files within npm module like lodash


Lodash allows import like

import merge from 'lodash/merge';

This reduces the size of the import drastically. I maintain an npm module called react-spinners, and I want to allow the same import.

https://github.com/davidhu2000/react-spinners

For example, the current way to import is

import { BarLoader } from 'react-spinners';

I want to allow

import BarLoader from 'react-spinners/BarLoader';

Based on what I found, to do this, I need to have the following folder structure

main
  - index.js <- the file that exports everything
  - BarLoader.js
  - ... other loaders

This structure is pretty messy because all the js files will be in the root directory.

The current set up I have is

main
  - index.js
  - dist <- output folder from compiling
    - index.js
    - BarLoader.js
  - src <- uncompiled react code
    - index.js
    - BarLoader.js

So, currently, in order to import only a single loader is

import BarLoader from 'react-spinners/dist/BarLoader';

I cannot find anything that tells me how I can remove the dist from the above statement.


Solution

  • If you really want to mess with the npm-package You can create a file like BarLoader.js on the main package folder and only export BarLoader(just like index.js exports every items)

    Then you can import it via

    import BarLoader from 'react-spinners/BarLoader';
    

    But I would not recommend it as it would be a tedious task to create one file for each import I guess it is a fair question, What is wrong with import BarLoader from 'react-spinners/dist/BarLoader';? maybe code readability?