es6:如何将依赖项添加到动态导入中



我想动态加载一个(角度(库,所以我使用import来加载该库。

import(/* webpackIgnore: true */ url).then(module => {
console.log('Got ya!');
});

我添加了/* webpackIgnore: true */,这样Webpack就不会在构建时尝试将其添加到捆绑包中。这似乎有效,但现在无法加载库的导入。我得到

TypeError: Failed to resolve module specifier "@angular/core". Relative references must start with either "/", "./", or "../".

这似乎是由导入外部库中的类引起的。例如

import {Component, EventEmitter, Input, Output} from '@angular/core';

我设法使用了SystemJS,但我想尝试在没有额外的SystemJS(6.6(库的情况下实现同样的效果。请参阅SystemJS 6.x设置/注册模块或在为该解决方案动态加载模块时提供映射。

但如果没有SystemJS,是否也可以加载外部模块的所有依赖项?或者更好的是,重用已经加载的依赖项,比如@angular/core。。。?

谢谢!

更新

我想我可以使用importmap,如下所述:https://medium.com/@dmnsgn/in-2020-go-bundler-free eb29c1f05fc9(https://github.com/guybedford/es-module-shims/blob/master/src/es-module-shims.js)。

这可以将@angular/core转换为类似./node_modules/@angular/core的内容。

剩下的问题是如何重用主机应用程序中已经加载的模块。在SystemJS中,我们可以注册这样的模块来使用,而不是提取。

只需通过import {...}从动态模块获取任何需要访问的依赖项,并将其放在全局范围内的某个位置。然后,创建一个导入映射,只需使用正确的名称从全局范围中重新导出值。一旦完成,您就可以在其他模块中使用import {...}以及顶层的import()来提取它们。

编辑:我为此创建了一个NPM模块:https://www.npmjs.com/package/import-mapper

// Preexisting class...
class Foo {};
// Put the class somewhere we can find it later...
globalThis['##IMPORTS##'] = { '@foo/Foo': Foo };
// Put the class in an importMap
const importMap = document.createElement('script');
importMap.setAttribute('type', 'importmap');
importMap.innerHTML = JSON.stringify({
imports: {
// This is the meat-and-potatoes of our shim:
'@foo/Foo': 'data:application/javascript;charset=utf-8,' + encodeURIComponent(
`export const Foo = globalThis['##IMPORTS##']['@foo/Foo']`
),
// This would actually live in a separate file:
'@bar/Bar': 'data:application/javascript;charset=utf-8,' + encodeURIComponent(`
import { Foo } from '@foo/Foo';
export class Bar extends Foo {};
`),
}
});
// Append the importMap to the document head
document.head.append(importMap);
// Clean it up.
importMap.remove();
// Check the imports
import('@foo/Foo').then(foo => console.log(foo));
import('@bar/Bar').then(bar => console.log(bar));

最新更新