Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Angular 12) The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script

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:
enter image description here

I tried adding "type": "module" in package.json and "module": "ESNext" in tsconfig.json, but with no luck.

How can I fix this?

like image 493
Two Horses Avatar asked Oct 27 '22 11:10

Two Horses


People also ask

Does angular support dynamic imports?

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.

What is webpackChunkName?

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].

How import works in webpack?

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.

What is dynamic import in react?

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.


1 Answers

Dynamic imports only works since ES2020. Please, check your tsconfig.json in order to know what version is your target.

like image 113
Ricardo Machado Avatar answered Oct 29 '22 14:10

Ricardo Machado