Writing NPM modules in Typescript 中有相关说明,但它已过时,现在有很多不同的答案可能会或可能不适用于Angular。 Jason Aden在youtube上有关于如何发布Angular Components的非常好的演示,但在这种情况下,我只对发布vanilla typescript类感兴趣。
答案 0 :(得分:2)
我完成了测试这个的原型。我使用了来自this article - creating npm modules written in typescript的代码和来自Jason Aden's Packaging Angular Presentation的汇总建议。
请注意,tsconfig-cjs.json
部分是这样的,除了支持webpack和Angular之外,我们还支持commonjs + es5工作流程。
mkdir tsmproducer
cd tsmproducer
# Initialize the project's package.json
npm init -y
package.json
: {
"name": "tsmproducer",
"version": "1.0.0",
"description": "Example typescript npm project supporting es6 modules via the module package.json attribute as well as commonjs",
"main": "target/main/cjs/index.js",
"types": "target/main/esm/index.d.ts",
"module": "target/main/esm/fesm.js",
"scripts": {
"build-cjs": "rm -rf target/main/cjs && tsc -p tsconfig-cjs.json",
"build-esm": "rm -rf target/main/esm && tsc -p tsconfig-esm.json && rollup target/main/esm/index.js -o target/main/esm/fesm.js",
"build-all": "npm run build-cjs && npm run build-esm"
},
"keywords": [
"typescript",
"commonjs",
"npm",
"modules",
"es6",
"es2015",
"publishing",
"rollup",
"treeshaking"
],
"author": "Ole Ersoy",
"license": "MIT",
"devDependencies": {
"rollup": "^0.41.6",
"typescript": "^2.3.4"
}
}
npm i
npm i -g rollup
npm i -g typescript
# Make typescript source directory
mkdir -p src/main/ts
# tsconfig-esm.json
{
"compilerOptions": {
"declaration": true,
"module": "es2015",
"target": "es5",
"rootDir": "src/main/ts",
"outDir": "target/main/esm"
},
"exclude": [
"node_modules"
]
}
# tsconfig-cjs.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"rootDir": "src/main/ts",
"outDir": "target/main/cjs"
},
"exclude": [
"node_modules"
]
}
# src/main/ts/printSubtract.ts
export function printSubtract(...numbers: number[]) {
console.log(`Subtracting the numbers: ${numbers.join(', ')}`);
}
# src/main/ts/printAdd.ts
export function printAdd(...numbers: number[]) {
console.log(`Adding the numbers: ${numbers.join(', ')}`);
}
# src/main/ts/index.ts
export * from './printAdd';
export * from './printSubtract';
npm run build-all
mkdir tsmconsumer (TS Module Consumer)
cd tsmconsumer
npm init -y
npm i ../tsmproducer
touch index.ts
在index.ts
中尝试以下操作:
import {printAdd, printSubtract} from 'tsmproducer';
printAdd(1, 2);
printSubtract(2, 1);
package.json's module
属性公开。target/main/esm
目录中,并通过package.json's types
属性公开。package.json's main
属性启用CommonJS模块支持。