我在Angular 2
项目中使用了这个es6-module-loader
,它非常适合在web浏览器中实时加载TypeScript
模块。现在,我正在将此项目升级到Angular 6
,但这里不满足加载模块的imports
的依赖关系。例如:
declare var SystemLoader:any;
export class DemoClass {
constructor() {
var source = "export class Foo { " +
"constructor() { console.log('Created the ES6 class foo!'); } " +
"execMethod() { console.log('Executed method!') }" +
"}";
SystemLoader.module(source, {name: _name}).then(function (module: any) {
module.Foo.prototype.execMethod();
}
}
}
前面的代码适用于Angular 6
。它将加载模块Foo
并在Console
中打印这些行。但如果我让模块稍微复杂一点,并添加一些import
,比如
declare var SystemLoader:any;
export class DemoClass {
constructor() {
var source = "import {Component} from "@angular/core"; " +
"export class Foo { " +
"constructor() { console.log('Created the ES6 class foo!'); } " +
"execMethod() { console.log('Executed method!') }" +
"}";
SystemLoader.module(source, {name: _name}).then(function (module: any) {
module.Foo.prototype.execMethod();
}
}
}
然后它就不起作用了,并向error 404 loading @angular/core
投诉。因此,在Angular 2
中,这是没有问题的,因为项目所需的所有node_modules
都是由Angular
按原样加载的,但在Angular 6
中,似乎所有这些依赖项都由Webpack
显示,并全部吐在一个大的JavaScript
文件中。那么,我如何绕过Webpack
简化,以便动态模块可以加载呢?
编辑:
或者至少使用上面公开的相同过程(加载源代码、编译[transfile]并在客户端机器中渲染(从es6-module-loader
(已弃用(迁移到es-module-loader
的示例。
我不熟悉angular 6,但这个问题似乎源于webpack的模块解析过程,在这个过程中,模块加载程序在编译时没有机会获取模块依赖关系。有几种方法可以解决这个问题。
假设@angular/core
是以兼容的方式(如公共js、umd等(声明的,您可以不将其添加为外部依赖项。如果尚未以这种方式声明,您可以始终在其周围创建一个包装来公开它,例如作为common-js
模块。
另一种方法是在这个依赖项上有一个代码拆分点(使用动态导入或require.ensure
(。我不确定它能不能做到,但如果相关的角度加载程序(将源文本解析为源代码的加载程序(有机会工作,并且它的输出是编译代码,它可能会工作。