【发布时间】:2018-10-13 02:15:21
【问题描述】:
很长一段时间以来,我一直非常习惯使用 Typescript 创建和使用 NPM 包,但这些包本质上是作为单个模块提供和使用的。我现在想发布包含多个模块的包,而不需要消费者在代码中导入比他们想要的更多的包。
假设我的包 src 文件夹中有两个 typescript 模块,一个在文件 one.ts 中,另一个在文件 two.ts 中:
one.ts:
export function talk() { console.log("Hello World"); };
两个.ts:
export function talk() { console.log("Goodbye World"); };
现在,使用在 Typescript 中创建 NPM 包的最佳实践,我还在我的 src 文件夹中创建 index.ts 文件:
index.ts:
import * as one from "./one";
import * as two from "./two";
export { one, two };
以及如何在我的包的 dist 文件夹中包含文件 index.js、index.d.ts、one.js、one.d.ts、two.js 和 two.d.ts(可能还有 source映射文件与此问题无关)。
这是(有点缩写的)package.json:
{
"name": "my-package",
"version": "0.0.5",
"description": "",
"license": "UNLICENSED",
"main": "dist/",
"types": "dist/",
"scripts": {
"build": "tsc --skipLibCheck",
"prepublish": "yarn run build",
},
"keywords": [],
"dependencies": {},
"files": [
"src",
"dist"
]
}
同样有点缩写的 tsconfig.json:
{
"compilerOptions": {
"target": "es6",
"module": "es6",
"moduleResolution": "node",
"noImplicitAny": true,
"noEmitOnError": true,
"removeComments": false,
"declaration": true,
"outDir": "./dist",
"allowJs": false,
"sourceMap": true,
"typeRoots": [
"./node_modules/@types"
]
},
"include": [ "src/**/*" ],
"exclude": [ "node_modules" ],
"compileOnSave": false
}
现在我发布该包并在 typescript 中使用它(当然,在 npm -i 之后),使用以下内容:
import * as conversation from "my-package"
conversation.one.talk(); // Hello World
conversation.two.talk(); // Goodbye World
但现在假设我只想导入模块 one.ts。我只会说“你好”,不会说“再见”。 重要提示:我什至不想将“再见”打包到我的消费代码中。(在我的例子中,我使用 webpack 来捆绑消费代码)。
所以我想以某种方式要求导入仅导入 one.ts。我真的不在乎语法是什么样子,只要我能做到:
import * as greeting from "my-package.one"; // I know this doesn't work
greeting.talk();
我也真的很想能够做到这一点:
import { talk } from "my-package.one"; // Again, I know this doesn't work
talk();
如果编写 javascript 并使用环境模块创建我自己的头文件,我知道该怎么做。但我不想做任何像那样花哨的事情。我只想使用模块作为模块,这些模块显然存在于包中,就像安装在节点模块中一样。
是否有任何建议修改我如何构建多模式包和/或如何使用它?
非常感谢。
【问题讨论】:
标签: typescript npm module package