Typescript + nodeJS:导入 fs 变成字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17927552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript + nodeJS: import of fs becomes string
提问by Guy
I'm new with Typescript and with NodeJS.
我是 Typescript 和 NodeJS 的新手。
For some reason this:
出于某种原因,这是:
GetMenuDataCommand.ts
获取菜单数据命令.ts
"use strict";
import fs = module("fs")
becomes this:
变成这样:
GetMenuDataCommand.js
获取菜单数据命令.js
var fs = "fs";
Typescript - i love you - but why?
打字稿 - 我爱你 - 但为什么呢?
采纳答案by Nathan Ridley
Are you referencing the node.d.ts
file correctly? If TypeScript doesn't have a reference to the definition file for your import, it'll generate a string for the import instead of the expected code.
您node.d.ts
是否正确引用了文件?如果 TypeScript 没有对导入的定义文件的引用,它将为导入生成一个字符串,而不是预期的代码。
For example, I had the following:
例如,我有以下内容:
import passport = require('passport');
and that was generating:
这正在产生:
var passport = "passport";
Turns out I'd forgotten to reference the definition file. Adding a reference at the top of the file solved the problem:
原来我忘了引用定义文件。在文件顶部添加引用解决了问题:
/// <reference path="../../definitions/passport.d.ts" />
Arguably you should spot it easily because the TypeScript compiler would throw an error, but 0.9.x is somewhat bug-ridden and it doesn't always catch everything.
可以说你应该很容易发现它,因为 TypeScript 编译器会抛出一个错误,但 0.9.x 有点漏洞百出,它并不总是能捕获所有内容。
回答by Fenton
I'm using TypeScript 0.9 the following code:
我正在使用 TypeScript 0.9 以下代码:
/// <reference path="node.d.ts" />
import fs = require("fs");
fs.appendFile('name.txt', 'Some data');
Produces the following identical output:
产生以下相同的输出:
var fs = require("fs");
fs.appendFile('name.txt', 'Some data');
(In CommonJS mode - in AMD mode it does the below...)
(在 CommonJS 模式下 - 在 AMD 模式下,它执行以下操作...)
define(["require", "exports", "fs"], function(require, exports, __fs__) {
var fs = __fs__;
fs.appendFile('name.txt', 'Some data');
});
回答by Rick
You are missing types.
你缺少类型。
From the command line.
从命令行。
npm install typings --save-dev
node node_modules/typings/dist/bin.js install dt~node --save --global
You must include the global
flag or else your text editor won't pick up the .dt.ts
file.
您必须包含该global
标志,否则您的文本编辑器将不会选择该.dt.ts
文件。
回答by basarat
Not sure if its related but in ts 0.9.x use require instead of module keyword :
不确定它是否相关,但在 ts 0.9.x 中使用 require 而不是 module 关键字:
"use strict";
import fs = require("fs")