I have the following dynamic import code to import a js library at runtime:
export class AuthService {
constructor() {
import('https://apis.google.com/js/platform.js').then(result => {
console.log(result)
})
}
}
However when I try to build/serve the Angular project I get:
external "https://apis.google.com/js/platform.js" - Error: The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script Did you mean to build a EcmaScript Module ('output.module: true')?
In addition, vs-code highlights the import
with the following:
I tried adding "type": "module"
in package.json
and "module": "ESNext"
in tsconfig.json
, but with no luck.
How can I fix this?
TypeScript 2.4 added support for dynamic import() expressions, which allow us to asynchronously load and execute ECMAScript modules on demand. This means that we can conditionally and lazily import other modules and libraries.
webpackChunkName : A name for the new chunk. Since webpack 2.6. 0, the placeholders [index] and [request] are supported within the given string to an incremented number or the actual resolved filename respectively. Adding this comment will cause our separate chunk to be named [my-chunk-name]. js instead of [id].
The imports loader allows you to use modules that depend on specific global variables. This is useful for third-party modules that rely on global variables like $ or this being the window object. The imports loader can add the necessary require('whatever') calls, so those modules work with webpack.
An example of dynamic imports is: const module = await import('/modules/myCustomModule. js'); Dynamic imports are asynchronous in contrast to static imports, which are synchronous. Thanks to this, we can now import our modules and files as needed.
Dynamic imports only works since ES2020. Please, check your tsconfig.json in order to know what version is your target.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With