【问题标题】:.net core 2.2 with typescript and signalr带有打字稿和信号器的.net core 2.2
【发布时间】:2019-09-06 14:24:32
【问题描述】:

我想拥有带有 TypeScript 和 Signalr 的 ASP.NET core 2.2,但我不知道如何正确设置项目。

我已经将@aspnet/signalr npm 包安装到带有npm install @aspnet/signalr 的项目根目录。所以我的项目根目录如下所示:

Controllers/
Models/
node_modules/
Properties/
TypeScript/
Views/
wwwroot/
appsettings.Development.json
appsettings.json
MyProject.csproj
package-lock.json
package.json
Program.cs
Startup.cs
tsconfig.json

拥有这个 TypeScript/home.ts 文件:

import * as signalR from "@aspnet/signalr";

const connection = new signalR.HubConnectionBuilder().withUrl("/gameHub").build();


connection.on("ReceiveMessage", function (user, color) {
    console.log("color " + color + "; user " + user);
    let canvas = <HTMLCanvasElement>document.getElementById(user).getElementsByClassName("board")[0];
    let context = canvas.getContext("2d");
    context.fillStyle = color;
    context.fillRect(0, 0, 200, 200);
});

最后是我的 tsconfig.json 文件:

{
  "compileOnSave": true,
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es2017",
    "outDir": "wwwroot/js"
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

当我在 tsconfig.json 中使用 "target": "es2017", 时,VS 找不到 @aspnet/signalr 并且我无法运行项目。当我将它切换到"target": "es5", 时,VS 可以找到@aspnet/signalr,但它会生成带有以下行的 home.js:Object.defineProperty(exports, "__esModule", { value: true });,它会在浏览器中引发错误。

我猜我的 tsconfig.json 设置不正确。如果可能的话,我也想在浏览器中使用 ES6 模块 (https://www.sitepoint.com/using-es-modules/)

【问题讨论】:

  • 这方面有什么更新吗?
  • 很遗憾没有,我仍在寻找可以在浏览器中使用 ES6 模块的解决方案。

标签: c# typescript asp.net-core signalr


【解决方案1】:

尝试关注这个tutorial

通常您必须以es5 为目标才能在浏览器的 Web 项目中运行。他的教程向您展示了如何使用 webpack 设置 typescript,因为我们需要将 ts 编译为 js

如果您需要任何帮助,请告诉我

【讨论】:

  • 这对我有用,但我有点希望在没有 webpack 的情况下做到这一点。我不喜欢让成千上万个不同的工具和应用程序运行来做一件事的想法。我认为只能通过 tsconfig.json 中的正确设置来完成。谢谢
  • 也许你需要配置你的 vs 来构建 ts 到 js
  • 顺便说一句。为什么我必须以 es5 为目标?我不能使用例如 es2017 吗?我也想在浏览器中使用模块,因为它们应该受到支持。
  • es5 以支持的浏览器为目标,例如 IE
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-01
  • 2019-11-22
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多