我有一个用TypeScript编写的Node.js和AngularJS应用程序,我正在尝试使用System.js加载模块 .
如果我只导入一个类来指定一个类型,它工作正常 . 例如:
import {BlogModel} from "./model"
var model: BlogModel;
但是,当我尝试使用导入的类实例化变量时,我在运行时获得异常 . 例如:
import {BlogModel} from "./model"
var model: BlogModel = new BlogModel();
未捕获的ReferenceError:未定义require
我使用CommonJS . 我不能使用AMD,因为我有一个服务器端和客户端项目 . 这就是我使用System.js在客户端加载模块的原因 .
这是我的System.js定义:
<script src="/assets/libs/systemjs-master/dist/system-polyfills.js"></script>
<script src="/assets/libs/systemjs-master/dist/system.src.js"></script>
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('classes.ts')
.then(null, console.error.bind(console));
System.import('model.ts')
.then(null, console.error.bind(console));
</script>
这是model.ts文件的内容:
import {User} from "./classes";
import {Post} from "./classes";
export class BlogModel{
private _currentUser: User;
private _posts: Post[];
get currentUser(){
return this._currentUser;
}
set currentUser(value: User){
this._currentUser = value;
}
get posts(){
return this._posts;
}
set posts(value: Post[]){
this._posts = value;
}
}
这是产生异常的JS行:
var model_1 = require("./model");
未捕获的ReferenceError:未定义require
任何帮助将深表感谢!
1 回答
让我们尝试简化一些事情:
1)按如下方式配置systemjs:
2)确保你的
classes.ts
和model.ts
和bootstrap.ts
(这是你应该创建的新文件,它将引导您的应用程序)文件被转换为与index.html位于同一目录中(index.html应该包含配置systemjs的脚本)如上所述)3)在bootstrap.ts中:
3)通过单次调用System.import来引导应用程序:
尝试这些步骤,我想你会解决你的问题 .