从node_modules

时间:2018-01-25 16:14:44

标签: javascript npm ecmascript-6

我目前正在开发一个软件包,在我的软件包存储库中,我有以下结构:

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

package.json内,我有以下内容:

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

然后在我的项目中,我执行以下操作来检索我的模块:

import Requests from 'package-name';

现在我想要实现的是从包中导入Constants类。但是,当我执行以下操作时,我收到一个编译错误,它无法找到该类。

import Constants from 'package-name/Constants';

要使其正常运行,我必须这样做,但我不想在导入路径中使用/src

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

我已尝试将main中的package.json更改为该目录,但它仍无效:

"main": "src/"

1 个答案:

答案 0 :(得分:3)

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.