PolyDeill for TextDecoder

sfl*_*che 8 javascript polyfills fetch-api

我正在使用fetch并将whatwg-fetchpolyfill包含在我的应用程序中.

我也TextDecoder按照Jake Archibald的博客中描述的那样使用了!解码响应,但我不确定使用什么polyfill.

(目前Safari抱怨ReferenceError: Can't find variable: TextDecoder)

我猜有一个polyfill TextDecoder,但我找不到它......

sfl*_*che 11

我能够通过使用text-encoding库来解决这个问题

npm install text-encoding --save
Run Code Online (Sandbox Code Playgroud)

随着

import encoding from 'text-encoding';
const decoder = new encoding.TextDecoder();
Run Code Online (Sandbox Code Playgroud)

  • 天哪!这是 [536 kB](https://bundlephobia.com/result?p=text-encoding@0.7.0) 不必要的膨胀。有关更高级的解决方案,请参阅 /sf/answers/4143185161/ 。用法完全相同:“从‘fastestsmallesttextencoderdecoder’导入编码;”,但没有任何膨胀。 (3认同)

Ros*_*res 8

现在,您可以使用MDN 网站推荐的FastestSmallestTextEncoderDecoder polyfill (1.5 KB) 。


Sph*_*xxx 7

对于快速的客户端测试(无NPM):

<script src="https://unpkg.com/text-encoding@0.6.4/lib/encoding-indexes.js"></script>
<script src="https://unpkg.com/text-encoding@0.6.4/lib/encoding.js"></script>
Run Code Online (Sandbox Code Playgroud)

..然后像平常一样使用TextDecoderMDN的示例:

<script src="https://unpkg.com/text-encoding@0.6.4/lib/encoding-indexes.js"></script>
<script src="https://unpkg.com/text-encoding@0.6.4/lib/encoding.js"></script>
Run Code Online (Sandbox Code Playgroud)
var win1251decoder = new TextDecoder('windows-1251');
var bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]);
console.log(win1251decoder.decode(bytes)); // ??????, ???!
Run Code Online (Sandbox Code Playgroud)