例子下载
需要require.js支持
index1.html
<script data-main="bin/index.js" src="require.js"></script>
tsconfig.json
{ "compilerOptions": { "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ "module": "umd", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "outDir": "bin", /* Redirect output structure to the directory. */ "strict": true, /* Enable all strict type-checking options. */ "sourceMap": true, //"baseUrl": "ts", //不要这个设置,会导致自动生成的import语句缺少./部分,运行时报找不到模块出错 //"esModuleInterop": true, //"moduleResolution": "node" } }
tasks.json
{ // See https://go.microsoft.com/fwlink/?LinkId=733558 "version": "2.0.0", "tasks": [ { "label": "build ts", "type": "typescript", "tsconfig": "tsconfig.json", "problemMatcher": [ "$tsc" ], "group": { "kind": "build", "isDefault": true } } ] }
launch.json
{ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Launch Chrome", //"url": "http://127.0.0.1:8000/index1.html", "url": "${workspaceFolder}/index1.html", "webRoot": "${workspaceFolder}" }, // { // "type": "node", // "request": "launch", // "name": "Launch Program", // "program": "${workspaceFolder}\\bin\\index.js", // //"preLaunchTask": "build ts", // //"cwd": "${workspaceFolder}/./bin", //修改执行node index.js 的路径 // "console": "internalConsole", //输出到 DEBUG CONSOLE (默认值) // "internalConsoleOptions": "openOnSessionStart", //每次运行自动转到 DEBUG CONSOLE 以显示输出内容 // "outFiles": [ // "${workspaceFolder}/**/*.js" // ] // } ] }
index.ts
import { M3 } from "./m3"; import { M2 } from "./m2"; let r1 = M1.MM1.C1.Add1(10, 20); document.write("r1, " + r1); //let r2 = M2.C2.Add2(10, 20); //C2没有export所以编译不了 let r3 = M3.C3.Add3(10, 20); document.write("<br>r3, " + r3);
m1.ts
module M1.MM1 { export class C1 { public static Add1(a:number, b:number) { return 100 * (a + b); } } }
m2.ts
export module M2 { class C2 //类不export就访问不到 { public static Add2(a:number, b:number) { return 200 * (a + b); } } }
m3.ts
export module M3 { export class C3 { public static Add3(a:number, b:number) { return 300 * (a + b); } } }