Importing an ESM module from a CDN with Webpack and Typescript

Viewed 947

I am working with a library that only offers it's functionality by importing it dynamically from a CDN. The usage is like this:

import LibraryClass from "https://cdn.com/library-url.esm.js";
const libraryInstance = new LibraryClass();

This works well on a simple example where I just load the vanilla.js script directly on the the html page. But I need to use it within a project that uses Webpack and TypeScript. If I try to build the project I get the following error:

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

My tsconfig looks like this:

 {
  "compilerOptions": {
    "target": "ES2018",
    "module": "esnext",
    "lib": ["es5","es6","dom","dom.iterable","ESNext"] ,
    "allowJs": true ,
    "jsx": "react",
    "declaration": true ,
    "sourceMap": true ,
    "composite": true,                       
    "strict": true,
    "noImplicitAny": false,
    "strictNullChecks": true ,
    "strictPropertyInitialization": false ,
    "moduleResolution": "node",          
    "baseUrl": "./packages",
    "esModuleInterop": true ,
    "allowUmdGlobalAccess": true ,
    "experimentalDecorators": true,
    "preserveConstEnums": true
  }
}

And my webpack.config like this:

{
    entry: './src/index.tsx',
    output: {
      path: path.resolve(__dirname, './dist'),
      filename: 'bundle.js'
    },
    resolve: {
      extensions: ['.ts', '.tsx', '.js'],
      alias: {
        src: path.resolve(__dirname, './src/')
      }
    },
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          loader: 'ts-loader',
          exclude: /node_modules/,
          options: {
            // disable type checker - we will use it in fork plugin
            transpileOnly: true
          }
        }
      ]
    },
    externals: {
      three: 'THREE'
    }
   ...
  };

I have tried different combinations but to no avail. Any ideas of how to get this working would be very much appreciated.

0 Answers
Related