我刚刚下载了新的 Visual Studio Code,我的第一印象非常好。对于 typescript ,智能感知工作得很好。
但是有个奇怪的问题:VS Code好像不能编译typescript模块。
这段代码:
/// <reference path="../definitions/react.d.ts"/>
import React = require("react");
在 cmd 上编译得很好,用
tsc --module commonjs main.ts
但在 VS Code 中,第二行以红色突出显示,编辑器提示:
cannot compile external modules unless the "-module" flag is provided
当然,任何使用模块的 typescript 代码都必须使用此标志进行编译。但是如果 IDE 知道模块的使用,为什么不设置标志呢?没有模块的 Typescript 代码在保存时编译,没有问题。
我想我缺少一些编译器设置配置文件。有这样的事吗?我在哪里可以找到它?
更新
我已经添加了 tsconfig.json 文件:
{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"sourceMap": true
}
}
这实际上消除了错误。不幸的是,IDE 不再编译我的代码。起初我以为 config.json 只会消除错误消息,但它的作用不止于此。 Intellisense 现在可以在示例文件中使用。如果我输入 React
,就会触发自动完成功能,并且显然知道 React,因为会显示有意义的建议。
现在,为什么 VS Code 不将文件编译为 js?我已经尝试配置任务运行器来完成这项工作,但它似乎不起作用:
{
"version": "0.1.0",
// The command is tsc.
"command": "tsc",
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Under windows use tsc.exe. This ensures we don't need a shell.
"windows": {
"command": "tsc.exe"
},
// args is the HelloWorld program to compile.
"args": ["--module commonjs","${file}"],
// use the standard tsc problem matcher to find compile problems
// in the output.
"problemMatcher": "$tsc"
}
如果我保存文件,什么也不会发生,即使我明确地运行构建任务,也没有任何响应。我编辑的任务名称是“tsc”,我也尝试运行它。没有效果。然后我将参数更改为 "args": ["--module commonjs","main.ts"]
,没有响应。
更新
task runner 似乎唯一的工作方式是使用这两个设置:
"args": ["${file}"], "isShellCommand": true,
这里是输出:
"args": ["-p"],
"args": ["-p", "."],
error TS5023: Unknown compiler option 'p'.
"args": ["."],
error TS6053: File '.ts' not found.
最佳答案
我今天也遇到了同样的问题。我点击了这个链接 http://blogs.msdn.com/b/typescript/archive/2015/04/30/using-typescript-in-visual-studio-code.aspx 完成所有设置步骤后,我在命令行上运行了这个命令,它开始生成 JavaScript 文件
npm install -g typescript
我们需要确保我们已经安装了 node 和 npm,并且可以通过命令行访问。
我发现它不起作用的原因是在 tasks.json
中我们指定了以下选项
"command": "tsc"
"isShellCommand": true,
因此,visual studio code 尝试在命令行上运行命令 tsc
,但没有找到 tsc
。因此,使用 npm 在全局安装 typescript 解决了这个问题。
关于typescript - Visual Studio Code : compile typescript module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30050262/