Typescript --allowJs 如何工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40089419/
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
How does Typescript --allowJs work?
提问by Oskar
I have read:
我读过了:
- TypeScript Roadmap 1.8
- JavaScript in TypeScript compilations
- Compilation of Js Files
- Announcing TypeScript 1.8 Beta
but I still don't get how it works and what it is good for. Could someone please explain what it is and when I would want to use it?
但我仍然不明白它是如何工作的以及它有什么好处。有人可以解释一下它是什么以及我什么时候想使用它吗?
采纳答案by Oskar
From Clay Allsopp on Medium:
allowJs is the option newly available in 1.8. The TypeScript compiler will run a quick sanity check on .js files for syntax errors but otherwise passes them straight through to the output directory.
allowJs 是 1.8 中新提供的选项。TypeScript 编译器将对 .js 文件运行快速健全性检查以查找语法错误,否则会将它们直接传递到输出目录。
This is useful when migrating a JavaScript project to TypeScript, that way you don't have to migrate everything at once but instead start writing new code in TypeScript and/or migrate each file one by one. You can find more information about migration from JavaScript to Typescript on the official site for TypeScript that has a tutorial called "Migrating from JavaScript".
这在将 JavaScript 项目迁移到 TypeScript 时非常有用,这样您就不必一次迁移所有内容,而是开始在 TypeScript 中编写新代码和/或逐个迁移每个文件。您可以在 TypeScript 的官方网站上找到有关从 JavaScript 迁移到 Typescript 的更多信息,该站点有一个名为“从 JavaScript 迁移”的教程。
回答by Martin
There are several uses for this. I am only going to go into one.
这有多种用途。我只会进入一个。
USE CASE: You are writing an application for web browsers. You want to write ES6 and have it transpiled to ES5.
用例:您正在为 Web 浏览器编写应用程序。您想编写 ES6 并将其转换为 ES5。
This is one of the use cases of --allowJs
. In a sense, it will do everything that the TypeScript compiler does except type check your code.
这是 的用例之一--allowJs
。从某种意义上说,它会做 TypeScript 编译器所做的一切,除了类型检查你的代码。
Without --allowJS
this would throw an error:
没有--allowJS
这个会抛出一个错误:
var foo = {};
foo.name = "bar";
This is because the type literal {}
does not have a property name
. This is valid JavaScript -- and therefore would not trip up the compiler with the type checking turned off.
这是因为类型文字{}
没有属性name
。这是有效的 JavaScript —— 因此不会在类型检查关闭的情况下绊倒编译器。
If you did want to use type checking you would refactor it to:
如果您确实想使用类型检查,您可以将其重构为:
var foo: any = {};
foo.name = "bar";
Or even better:
或者甚至更好:
var foo = {name: "bar"};