安装:
npm install --save @types/js-base64
引入:
import { Base64 } from '@types/js-base64';
然后,开始报错:js-base64/index.d.ts' is not a module
那么TYPScript到底应该如何引入第三方包呢?
参考一下这篇文章:
https://segmentfault.com/a/1190000008605017
解决方法一:
1、使用Typings安装:
//1、安装typings
npm install -g typings
//2、使用typings 查找资源,支持模糊查找
typings search base64
//3、安装ts库
typings install base-64 --save
//4、安装js库,注意与ts库名字一致
npm install base-64 --save
2、安装完成后,开始使用:
import * as Base64Tool from 'base-64';
let res1 = "hello,mengmeng儿~";
let ret = Base64Tool.encode(encodeURIComponent(res1));
console.log("ret: ",ret);
console.log(decodeURIComponent(Base64Tool.decode(ret)));
OK,搞定!
解决办法二:
@types的使用(推荐):
在项目目录下运行:
npm install –-save @types/库名
实测下:
npm install --save @types/pako
npm install --save pako
安装OK!
package.json:
PS:为什么要用 encodeURIComponent 、decodeURIComponent 进行编码?
解释:当字符串中含有中文时,base64转码时会提示:
The string to be encoded contains characters outside of the Latin1 range 。
江湖人传的最佳做法:
function utf8_to_b64(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
function b64_to_utf8(str) {
return decodeURIComponent(escape(window.atob(str)));
}
然后查了一下unescape:
既然官方这么建议了,我已不再尝试,通过测试用 encodeURIComponent 即OK。
作为一名曾经的phper,补充一句:
decodeURIComponent( ) encodeURIComponent( ) 对应php 中的 urldecode( ) 、 urlencode( )
总结:
1、新手入门,多遇到一些稀奇古怪的问题,要淡然看待,解决的过程即为成长;
2、在新手入门时,不要轻信别人的教程文档,原因两点,一、作者和你技术栈区别大时,重点步骤可能不同;二、作者可能犯错,比如缺少某个步骤,凑巧其他途径已弥补的情况;遇到这种情况,只能多尝试,多参考更多的资料;
3、不要当新手太久,新手依赖死规矩,且新手容易把概念理解错,思维受限,知识背景受限,赶紧变身!像专家那样用感觉还能精准的解决问题吧!