React Native 参考错误:找不到变量:文本编码器

bsxbgnwa  于 2022-11-25  发布在  React
关注(0)|答案(3)|浏览(249)

我正在为React Native项目使用VSCode/Typescript React 3.4.3,但在运行时使用TextEncoder时遇到问题
ts代码:

...
var encoder = new TextEncoder();
var b: Uint8Array = encoder.encode(newName);
...

我的tsconfig库:

"module": "es2015",
    "target": "es2015",
    "jsx": "react",
    "lib": ["es5", "es2017", "dom"]

此编译可以正常运行,但在运行时尝试创建TextEncoder示例时失败:
“引用错误:找不到变量:文本编码器”
我不明白这里出了什么问题。
任何帮助都很感激

EDIT 1:事实是,当你调试JS代码时,它会在Chrome中运行,这会导致成功。但当你不这样做时,你会发现JavaScriptCore既不支持TextEncorder,也不支持btoa。

因此,我选择使用npm模块(text-encodingbase-64):

import * as encoding from 'text-encoding';
import {encode as btoa} from 'base-64'
...
var encoder = new encoding.TextEncoder();
...
qvtsj1bj

qvtsj1bj1#

我在使用stomp.js套接字时遇到了同样的错误。
我所做的只是
从'text-encoding'导入 * 作为编码;
在App.js中,并且在发布和调试中都能正常工作

llew8vvj

llew8vvj3#

对于那些在2022年仍然有问题的人,或者 typescript 项目,请执行以下步骤:
1.运行:yarn add text-encoding
1.运行:yarn add big-integer
1.将以下代码添加到App.js或App.tsx:

const TextEncodingPolyfill = require('text-encoding');
const BigInt = require('big-integer')

Object.assign(global, {
    TextEncoder: TextEncodingPolyfill.TextEncoder,
    TextDecoder: TextEncodingPolyfill.TextDecoder,
    BigInt: BigInt,
});

相关问题