我想知道是否可以使用以不同版本的Angular构建的不同角度元素(自定义元素)。我听说zone.js污染了全球范围。
感谢您的回答。
虽然引导了多个元素,但我们可以添加不加载/修补zonejs的逻辑(如果已经按如下所示加载:)
从polyfill.ts中删除所有Angular元素的zonejs polyfill
创建main.ts
级别的文件。假设bootstraper.ts:
export class Bootstrapper {
constructor(
private bootstrapFunction: (bootstrapper: Bootstrapper) => void
) {}
/**
* Before bootstrapping the app, we need to determine if Zone has already
* been loaded and if not, load it before bootstrapping the application.
*/
startup(): void {
console.log('NG: Bootstrapping app...');
if (!window['Zone']) {
// we need to load zone.js
console.group('Zone: has not been loaded. Loading now...');
// This is the minified version of zone
const zoneFile = `/some/shared/location/zone.min.js`;
const filesToLoad = [zoneFile];
const req = window['require'];
if (typeof req !== 'undefined') {
req(filesToLoad, () => {
this.bootstrapFunction(this);
console.groupEnd();
});
} else {
let sequence: Promise<any> = Promise.resolve();
filesToLoad.forEach((file: string) => {
sequence = sequence.then(() => {
return this.loadScript(file);
});
});
sequence.then(
() => {
this.bootstrapFunction(this);
console.groupEnd();
},
(error: any) => {
console.error('Error occurred loading necessary files', error);
console.groupEnd();
}
);
}
} else {
// zone already exists
this.bootstrapFunction(this);
}
}
/**
* Loads a script and adds it to the head.
* @param fileName
* @returns a Promise that will resolve with the file name
*/
loadScript(fileName: string): Promise<any> {
return new Promise(resolve => {
console.log('Zone: Loading file... ' + fileName);
const script = document.createElement('script');
script.src = fileName;
script.type = 'text/javascript';
script.onload = () => {
console.log('\tDone');
resolve(fileName);
};
document.getElementsByTagName('head')[0].appendChild(script);
});
}
}
main.ts
中,我们可以将引导程序逻辑更改为以下逻辑:import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { Bootstrapper } from './bootstraper'; const bootstrapApp = function(): void { platformBrowserDynamic() .bootstrapModule(AppModule) .then(() => {}) .catch(err => console.error(err)); }; const bootstrapper = new Bootstrapper(bootstrapApp); bootstrapper.startup();
这样,我们绝对可以创建多个Angular Elements(Web组件)并在SPA中使用。
谢谢