Visual Studio 2017 无法更改 project.csproj 的 <TypescriptModuleKind> 用于打字稿转译

Visual Studio 2017 can't change project.csproj's <TypescriptModuleKind> for typescript transpiling

这是我在 的回答。

我需要将 t运行spiler VS 使用的模块类型更改为 AMD。它默认为 commonjs,即使 <TypescriptModuleKind>project.csproj 中从 commonjs 更改为 AMD

查看问题:

  1. 添加 typescript 插件 - Typescript 工具、Typescript 构建和 Rich Newman 的 Typescript HTML 应用程序模板。
  2. 使用模板创建新项目
  3. 观察 project.csproj 包含 <TypescriptModuleKind>commonjs</TypescriptModuleKind> 并保持原样
  4. 启动服务器。它启动正常,可以看到应用程序 运行(开发人员控制台中没有错误消息)
  5. 打开 app.js 文件并观察其开头为:

    "use strict";      
    var Greeter = /** @class */ (function () {
        function Greeter(element) {
    
  6. 打开app.ts并加上export作为前缀使其成为export class Greeter {

  7. 刷新页面,观察开发者控制台报错exports is undefined
  8. 打开 app.js 文件并观察它现在显示以下内容:

    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Greeter = /** @class */ (function () {
    
  9. 创建 tsconfig.json 运行 tsc --init

  10. 观察它包含"module": "commonjs"
  11. 运行 tsc 到 t运行spile ts 文件
  12. 观察 app.js 文件仍然如上(并且会导致 exports is not defined 错误)
  13. 更改 tsconfig.json 文件,使其包含 "module": "amd"
  14. 运行 tsc 到 t运行spile ts 文件
  15. 打开 app.js 文件并观察它现在显示以下内容:

      define(["require", "exports"], function (require, exports) {
          "use strict";
          Object.defineProperty(exports, "__esModule", { value: true });
          var Greeter = /** @class */ (function () {
    
  16. 按照 设置使用 requirejs :-)

  17. 刷新并观察它在浏览器中运行,没有显示任何错误
  18. tsconfig.json 重命名为 xxxxtsconfigxx.xxjson
  19. 停止服务器;修改 app.ts 文件使其变脏;重启服务器
  20. 观察 exports is not defined 错误已返回
  21. 如果愿意,将文件重命名为 tsconfig.json 并重复最后一步,观察错误仍然存​​在。这确认VS没有使用本地tsconfig.json进行配置。
  22. 修改 project.csproj 以包含 <TypescriptModuleKind>amd</TypescriptModuleKind>
  23. 停止服务器;修改 app.ts 文件使其变脏;重启服务器
  24. 观察 exports is not defined 错误已返回

从而证明 VS 不支持 tsconfig.json 文件并且似乎忽略了它的 TypescriptModuleKind 配置值。

What are the TypeScript project build configuration options?好像说的是VS是怎么用tsc的。我 运行 使用 --module 开关并且它工作正常(例如 tsc --module commonjs [app.ts]tsc --module amd [app.ts])。如果 tsconfig.json 文件不存在,则需要 [app.ts]。因此,VS 似乎忽略了 TypescriptModuleKind 设置或未以应有的方式应用它。

那么这是怎么回事。有没有办法让它使用 tsconfig.json 文件或遵循其 TypescriptModuleKind 设置?

我找到了答案。

在项目的属性中有一个 Typescript Build(侧面)选项卡和一个标记为 Module System 的下拉菜单,我将其设置为 'AMD'。这奏效了!太棒了。

@Chris Halcrow 在评论中建议,如果您从项目文件中取出 Typescript 配置,则 VS 可能会使用 tsconfig.json 中的配置。我没有尝试过,但如果您需要比 VS 提供的选项更多的选项,那绝对值得一试。


我刚找到 https://developercommunity.visualstudio.com/content/problem/24584/cant-compile-the-ts-files-on-vs2017-node-modules-n.html,其中有一些关于 VS 如何处理打字稿的有用信息。

我也意识到@ChrisHalcrow 说的 "if there's a tsconfig.json inside a project folder then the VS TS Config is ignored" 是正确的。我没有强迫 VS 识别 tsconfig.json 文件。一旦我再次添加它,它就会被看到。我忘记了 VS 需要“添加”东西(源文件、配置文件等)。我习惯了 Eclipe 和 IDEA 看到变化并询问或只是做。

更厉害!