简体   繁体   中英

Import more than one class from node_modules

I'm currently developing a package, and inside my package repository I have the following structure:

src
  - Requests.js
  - Constants.js
package.json

Inside my package.json , I have the following:

{
    "name": "package-name",
    "version": "1.0.0",
    "main": "src/Requests"
}

Then inside my project, I do the following to retrieve my module:

import Requests from 'package-name';

Now what I'm trying to achieve is to import the Constants class from the package. However, when I do the following, I get a compiled error that it cannot locate the class.

import Constants from 'package-name/Constants';

To get it working, I have to do but I don't want to have the /src in the import path.

import Constants from 'package-name/src/Constants';

I've tried to change the main in my package.json to the directory, but it's still not working:

"main": "src/"

Right, this is not a bug, just how node imports are handled by your bundler. There are many solutions to this problem, here are a couple:

The most user friendly is to have your publish command copy those components to the root directory and then publish. That way you'll be able to import like you say, import Constants from 'package-name/Constants' . It's only slightly inconvenient for you as a developer but a script should be able to clean up after the publish command succeeds.

An alternate solution is to have a third file, maybe call it index.js that looks somewhat like this:

import Requests from './Requests';
import Constants from './Constants';

export default {
   Requests,
   Constants,
};

This will allow you to import like this (don't forget to change your package.json to have "main": "src/index.js" ):

import { Requests, Constants } from 'package-name';

The only reason I would shy away from this approach is that when this import statement is handled by the bundler, ALL components are imported, even if you only need one of them. It could make your bundle larger if your library contains many different components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM