ayy*_*ddi 22 types node.js typescript typescript1.4 typescript1.8
我正在尝试使用TypeScript在NodeJS中执行base64编码.
以下代码在JavaScript中正常工作.
当我在TypeScript中编写相同的东西并进行编译时,我得到Buffer is not find错误.
var base64Policy = new Buffer(stringPolicy, 'utf-8').toString('base64');
Run Code Online (Sandbox Code Playgroud)
有人可以帮我在TypeScript中做同样的事情.
Dar*_*ght 37
在顶部添加此行:
declare const Buffer
Run Code Online (Sandbox Code Playgroud)
它应该编译没有错误.
使用内置库或其他全局对象的节点需要声明,您可以像上面一样手动声明它.
使用新版本的Typescript,您还可以使用官方声明文件:
npm i -g typescript@next
npm i --save-dev @types/node
Run Code Online (Sandbox Code Playgroud)
对于其他库,请安装@types/library_name.
Jay*_*nis 30
对于 IONIC 4 开发人员,我使用
npm install --save @types/node
当我尝试添加时安装它"types": ["node"],如下所示
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": ["node"]
},
Run Code Online (Sandbox Code Playgroud)
到
tsconfig.json
它没有工作。我不得不将条目添加到
tsconfig.app.json
请参阅以下链接以获取相关文档。
https://github.com/aws/aws-sdk-js/issues/1271#issuecomment-291658668
让我知道这是否对你有用!
Ben*_*uer 20
序幕
Buffer是Node.js API的一部分.因为默认情况下TypeScript不知道Node.js中的类,所以您需要为Node.js 安装声明文件(类型定义).
如果看到以下错误,则必须手动安装类型定义:
错误TS2304:找不到名称'Buffer'.
安装类型定义
您可以使用typings工具安装类型定义.我会告诉你如何做到这一点:
typings使用npm 安装该工具:
npm install -g typings
从DefinitelyTyped(~dt)存储库安装Node.js的类型定义:
typings install dt~node --global --save
打字工具将创建以下目录" typings/globals/node"并将其链接在" typings/index.d.ts"中.还会有一个名为typings.json(因为该--save选项)的文件,它引用了已解析的类型定义:
{
"globalDependencies": {
"node": "registry:dt/node#6.0.0+20160621231320"
}
}
Run Code Online (Sandbox Code Playgroud)
注意:如果您看到错误"typings\globals \node\index.d.ts(71,26):error TS1110:Type expected",那么您的Node.js定义太新了.打字工具有最新类型声明的问题.在这种情况下,只需检查typings.json文件中的版本即可.对我来说node#6.0.0+20160621231320工作但node#6.0.0+20161212163245不是.
index.d.ts作为三斜杠指令代码中(使用Buffer类):YourClass.ts
/// <reference path="../../typings/index.d.ts" />
export class YourClass {
private static toString(encoded: string): string {
return new Buffer(encoded, "base64").toString();
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
随着TypeScript 2.0的发布,一种新的类型定义系统已经公布.
你现在可以忘记这个typings工具了.您需要做的就是运行此命令来为Node.js安装TypeScript定义:
npm install --save @types/node
另外,请确保您的以下条目tsconfig.json:
{
"compilerOptions": {
"moduleResolution": "node",
...
},
"exclude": [
"node_modules",
...
]
}
Run Code Online (Sandbox Code Playgroud)
PS如果您需要其他类的类型定义(包含在Node.js中),您可以在此处搜索它们:http://microsoft.github.io/TypeSearch/
缓冲区来自Node名称空间。首次安装
npm install --save @types/node
然后将以下代码添加到tsconfig.json该compilerOptions部分中的文件中
"types": ["node"],
"typeRoots": ["node_modules/@types"]
Run Code Online (Sandbox Code Playgroud)
该typeRoots条目指定要包含的类型定义文件的目录列表。它需要TypeScript 2.0或更高版本。
对于 Angular 用户:
npm install --save @types/node
tsconfig.app.json文件中,将这两行添加到 CompilerOptions:"compilerOptions": {
//...
"types": ["node"],
"typeRoots": ["node_modules/@types"]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30202 次 |
| 最近记录: |