我想使用Typescript创建一个库。这个库可以在Node和浏览器环境中使用,因此配置提供了对的支持
(tsconfig.json(
{
"compilerOptions": {
"baseUrl": ".",
"declaration": true,
"esModuleInterop": true,
"lib": [ "esnext", "dom" ],
"module": "commonjs",
"outDir": "dist",
"resolveJsonModule": true,
"strict": true,
"target": "es2019",
},
"include": [
"./**/*.ts"
],
"exclude": [
"./dist"
]
}
我使用esbuild作为绑定器。包.json包含
{
"name": "my-lib",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc && esbuild ./dist/index.js --bundle --minify --sourcemap --outfile=./bundle/index.js"
},
"dependencies": {
"esbuild": "0.14.36"
},
"devDependencies": {
"typescript": "4.6.3"
}
}
图书馆利用了一些";私人的";helper函数,我使用以下示例代码
import { TextEncoder } from 'util';
const encodeInput = function (input: string): Uint8Array {
const textEncoder = new TextEncoder();
return textEncoder.encode(input);
}
运行build脚本命令会抛出一个esbuild错误,告诉我这只适用于Node环境,而不适用于浏览器,这是有道理的,因为
- 这个类来自
util
包https://nodejs.org/api/util.html#class-utilextendcoder - 该类不需要在浏览器环境中进行任何导入https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder
我如何确保这个库在";两个";世界?
TextEncoder
在Node中是全局的,所以不需要import
。直接使用它,不需要使用import
语句,就像在浏览器中一样。
您也不需要每次调用函数时都实例化一个新的
TextEncoder
:实例化一次,然后只别名encode
方法,这是一个小的性能优化。请参见下文。
const encoder = new TextEncoder();
const encode = encoder.encode.bind(encoder);
console.log(encode('hello world'));
您可以使用UMD(通用模块定义(工具来解决这个问题。
在tsconfig.json
中,只需将module: "commonjs",
更改为module: "umd",
,它就可以从那里正确构建,从而在所有环境中都可以工作。