エクスポートとインポートを使用しようとしていますが、うまくいきません。
以下は私のコード 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>
User.ts:
export class User {
firstName: string;
lastName: string;
}
main.ts
import { User } from "./user";
以下は、例外のスクリーンショットです。
選択肢は2つあります。
オプション1: Webpack、Browserifyなどのモジュールローダーを使用する。
Option 2: モジュールのインポートやエクスポートを行わずに、*.ts
から *.js
へコンパイルしたい場合は、tsconfig.json
で compilerOptions.module
を "none" に設定します。compilerOptions.module` を "none" に設定すると、モジュールのエクスポート/インポートができなくなることに注意してください。
以下の変更を試してみてください。
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>
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"sourceMap": true,
"outFile": "~/scripts/main.js",
"lib": [
"dom",
"es2015",
"es5",
"es6"
]
}
}
この設定では、出力は、main.tsのすべての参照ファイルを含む、wunderfullと醜く表現できる1つのjsファイルのみです。
ユーザー.ts
class User {
firstName: string;
lastName: string;
}
Main.ts。
/// <reference path="User.ts" />
// import { User } from "./user"; // not needed if referenced
console.log(new User());
すべての参照宣言は、ファイルの先頭に記述する必要があります。
TypeScriptはデフォルトでnode module resolutionを使用します。Node.js / CommonJSでは、exportsキーワードを使用します。しかし、CommonJSはモジュールローダーやモジュールバンドルラーを使わないとブラウザで動作しません。そのため、ブラウザで動作させるためには、browserify や webpack が必要です。
こちらのリンク https://www.typescriptlang.org/docs/handbook/gulp.html をご覧ください。
また、tsconfig.json の compiler options セクションで module 設定を none に設定することもできます。
{ compilerOptions"。{ "target": "es5", "module": "none" }