简体   繁体   English

如何分发带有子模块的 es6 包

[英]How to distribute an es6 package with submodules

I am trying to publish a package on npm.我正在尝试在 npm 上发布一个包。 I'm not sure how to phrase what I am trying to do..maybe packaging "sub modules"?我不知道如何表达我想要做的事情……也许包装“子模块”?

The abbreviated directory structure is:简写的目录结构为:

- package.json
- src/
  - a.js
  - b.js
- dist/
  - a.js
  - b.js

My build script uses Babel to transpile to the dist directory with the same modules as in src/ .我的构建脚本使用 Babel 转译到dist目录,其模块与src/模块相同。 I would like consumers to import functions from the a.js module like so:我希望消费者从a.js模块导入函数,如下a.js

import {foo} from "mypackage/a";

not不是

import {foo} from "mypackage/dist/a";

If I add an index.js to mypackage/ and export a I can do如果我将index.js添加到mypackage/并导出a我可以做

import {a} from "mypackage"

but that's not what I want...但这不是我想要的......

What is the standard way to publish packages so "sub modules" can be imported like this or can someone point me to a repo that does this kind of thing?发布包的标准方法是什么,以便可以像这样导入“子模块”,或者有人可以将我指向执行此类操作的存储库?

If I understand, there should be two options that you can choose.如果我理解,应该有两个选项可以选择。

First, let me try to explain how Node sub-modules with a slash are handled by Node.首先,让我尝试解释 Node 是如何处理带有斜线的 Node 子模块的。 When you import the module with a slash, Node will try to look in the root folder for a file with the name that is specified after the slash.当您使用斜杠导入模块时,Node 将尝试在根文件夹中查找具有斜杠后指定名称的文件。 In your case, it will be a.js .在您的情况下,它将是a.js In case nothing is found, Node will try to look for the directory named a containing the file index.js .如果没有找到,Node 将尝试查找名为a包含文件index.js的目录。 If no file is found, nothing is imported.如果未找到文件,则不会导入任何内容。

So back to your problem, you can either create file a.js in your root folder containing the following export:回到您的问题,您可以在包含以下导出的根文件夹中创建文件a.js

export * from './dist/a';
// The traditional export should look like this, in case I have wrong ES6 export
module.exports = require('./dist/a')

or change the structure of your project a bit, so files a and b are located in their specific directories.或稍微更改项目的结构,使文件ab位于其特定目录中。

For example:例如:

- package.json
- src/
  - a.js
  - b.js
- a/
  - index.js
- b/
  - index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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