gpt4 book ai didi

javascript - 在 Node 和浏览器环境中使用 TextEncoder 类

转载 作者:行者123 更新时间:2023-12-05 04:31:19 81 4
gpt4 key购买 nike

我想使用 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 用作 bundler 。 package.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"
}
}

该库使用了一些“私有(private)”辅助函数,我正在使用以下示例代码

import { TextEncoder } from 'util';

const encodeInput = function (input: string): Uint8Array {
const textEncoder = new TextEncoder();

return textEncoder.encode(input);
}

运行构建脚本命令会抛出一个 esbuild 错误,告诉我这只适用于 Node 环境,不适用于浏览器,这是有道理的,因为

我怎样才能确保这个库在“两个”世界中都能正常工作?

最佳答案

TextEncoder is a global在 Node 中,所以你不需要 import 它。直接使用它,无需 import 语句,就像在浏览器中一样。

You also don't need to instantiate a new TextEncoder every time the function is invoked: it is a small performance optimization to instantiate it once, and then just alias the encode method. See below.

const encoder = new TextEncoder();
const encode = encoder.encode.bind(encoder);

console.log(encode('hello world'));

关于javascript - 在 Node 和浏览器环境中使用 TextEncoder 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71856643/

81 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com