当我尝试导入外部模块并尝试编译我的代码时,出现以下错误消息:app.ts:1 Uncaught ReferenceError: require is not Define at app.ts:1
。 typescript 版本是:2.1.6。
我的 app.ts 文件:
import {PI, calcCircumference } from "./math/circle";
console.log(PI);
console.log(calcCircumference(10));
//console.log();
我的circle.ts文件
export const PI: number = 3.14;
export function calcCircumference(diameter: number) {
return diameter * PI;
};
我的 tsconfig.json 文件
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": true
}
}
谢谢大家
最佳答案
我假设您正在尝试在客户端环境(您的浏览器)中运行代码。在这种情况下,您必须配置模块加载器,因为与 Node.js 等服务器环境不同,浏览器默认不支持模块加载,并且不知道如何“需要”特定模块。
这里有多种选择:
- 捆绑工具,如 browserify/webpack
- 像requirejs这样的加载器/systemjs
Google 上您会发现很多有关如何使用上述内容之一设置 typescript 的教程(例如: systemjs 、 webpack )
我个人偏好是 systemjs (使用 jspm 作为包管理器) - 但您的选择将在很大程度上取决于您构建的应用程序的具体要求。
关于javascript - 导入/导出模块 - Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43900230/