'delay NgModule declaration with async import module
I would like to dynamically import a third-party module and check it. Then declaration in NgModule depends on it exist or not(true/false). Something like my code below. The problem is: the dynamically import is a Promise. I need that NgModule declaration AFTER the import Promise has loaded. How could i solve it?
let loaded = false;
import('ngx-color-picker').then((module) => {
console.log(module);
loaded = true;
}); // => it takes time
// the Module suddenly declaration => i need to delay it somehow and
// runs AFTER the above import Promise has loaded
@NgModule({
declarations: [
loaded ? SmNgxColorPickerComponent : [],
],
imports: [
// --- Angular Base imports ---
CommonModule,
ReactiveFormsModule,
// --- Angular Material imports ---
MatInputModule,
// --- Vendor imports ---
loaded ? ColorPickerModule : [],
],
exports: [
loaded ? SmNgxColorPickerComponent : [],
],
providers: []
})
export class SmNgxColorPickerModule {
}
Solution 1:[1]
In the newest esnext it's now possible to do it using top level await. (https://github.com/tc39/proposal-top-level-await)
to enable top level await for Angular:
- use esnext (es2022) in module and es2017 or higher in target (tsconfig.json)
"target": "es2017", // or higher
"module": "esnext",
- enable experiments.topLevelAwait for webpack (webpack.config.js)
module.exports = {
experiments: { topLevelAwait: true }
};
- you can now use await outside async functions
const fix = await import('library').then(
_ => loaded = true
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | frameworks_r_weird |