How to configure Webpack to build without importing an external module?

I Have a third-party library needed to be used in project ts code, which is added to the application using a CDN path in the HTML. And this library is exporting a window variable, which is used in the code.

The package is not available as an npm module. While running the webpack build it’s failing with the following error message: error TS2304: Cannot find name 'CUSTOM_WINDOW_VARIABLE'.

I have added this in name in the webpackconfig.js file as :

    externals: {
      CUSTOM_WINDOW_VARIABLE: "CUSTOM_WINDOW_VARIABLE",
    },

But still getting the same error.

How to tell webpack to ignore these global variables while building. Or convert them to window.CUSTOM_WINDOW_VARIABLE from CUSTOM_WINDOW_VARIABLE.

Answer

As I know your problem is not about webpack at all. The issue is most likely throwing from ts-loader which uses tsc compiler your tsx? files so in order to fix this issue you might need to define the type for your global value which is available on window as following steps:

  • Create your project typing dir and the file types/global.d.ts (you can name whatever you want, feel free to use my suggested name in terms of no idea how to name it) with following content:
// global.d.ts

// You can define your own type by replacing with the exact type
declare const CUSTOM_WINDOW_VARIABLE: any;
  • Make sure your tsconfig.json which is placed at repo’s root dir in most cases includes your types dir by adding to include config option:
// tsconfig.json
{
  "include": ["types", ...]
}

Hopefully it would work for your case

PS: If you don’t import your library as externals, basically you don’t have to configure the externals property in your webpack.config file