未定义TypeScript导出

Deo*_*tay 37 model-view-controller typescript

我正在尝试使用导出和导入但它无法正常工作我收到错误

这是我的代码HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    @RenderBody()

    <script src="~/scripts/user.js"></script>
    <script src="~/scripts/main.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

用户:

export class User {
    firstName: string;
    lastName: string;
}
Run Code Online (Sandbox Code Playgroud)

main.ts

import { User } from "./user";
Run Code Online (Sandbox Code Playgroud)

这里也是异常的截图:

在此输入图像描述

Sar*_*ana 20

你有几个选择:

选项1:使用Webpack,Browserify等模块加载器.

选项2:如果您只想编译*.ts*.js没有任何模块导入或导出,请compilerOptions.module在您的tsconfig.json.中设置为"none" .请注意,当您设置compilerOptions.module为"none" 时,将无法导出/导入模块.

  • 或者只是使用引用,而不是没有任何模块加载器和commonjs,你不想在你的html中加载数百个js文件,所以只输出1个js文件 (4认同)

Typ*_*rce 14

尝试以下更改

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    @RenderBody()

    <!-- <script src="~/scripts/user.js"></script> --> <!-- not longer needed -->
    <script src="~/scripts/main.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "outFile": "~/scripts/main.js",
    "lib": [
      "dom",
      "es2015",
      "es5",
      "es6"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

使用此配置,您的输出只是一个js文件,可以使用wunderfull,包含main.ts中的所有引用文件.我只是不知道是否〜/工作或者你是否必须设置相对于配置文件的路径,我不使用linux.

User.ts

class User {
    firstName: string;
    lastName: string;
}
Run Code Online (Sandbox Code Playgroud)

Main.ts:

/// <reference path="User.ts" />

// import { User } from "./user"; // not needed if referenced
console.log(new User());
Run Code Online (Sandbox Code Playgroud)

所有引用声明都必须写在文件的开头

  • 哇,我一直在搜索导入vs参考太多小时了,非常感谢你!这是我问题的根源. (3认同)
  • 这个答案对我不起作用,我遇到了这个问题:/sf/ask/2517434251/ (3认同)
  • 我收到“错误 TS6082:仅支持 'amd' 和 'system' 模块以及 --outFile” (2认同)

Ibr*_*bro 6

默认情况下,TypeScript 使用节点模块解析。Node.js / CommonJS 使用exports关键字。但是,CommonJS 不能在没有模块加载器或模块捆绑器的浏览器中运行。因此,您需要 browserify 或 webpack 才能让它在浏览器中运行。

查看此链接https://www.typescriptlang.org/docs/handbook/gulp.html

您还可以在tsconfig.json 的编译器选项部分将模块设置设置为无:

{ "compilerOptions": { "target": "es5", "module": "none" } }

  • 这不正确。我在浏览器中运行 CommonJS 没有任何问题。你不能在没有模块加载器的情况下在浏览器中使用导出和导入,这是正确的。 (2认同)