basarat / typescript-collections

A generically typed set of collections for use with TypeScript
MIT License
1.21k stars 161 forks source link

TypeError: ... is not a constructor when bundling with webpack 5 #120

Open blu3r4y opened 4 years ago

blu3r4y commented 4 years ago

I am not sure if this is an error with typescript-collections but since I upgraded to webpack 5 this package is the only one that has issues and I wonder what's the problem here. It worked back then with webpack 4.

Consider the following code, which I also pushed to https://github.com/blu3r4y/typescript-collections-webpack so that you can directly check it out and investigate the issue.

src/main.ts

import * as Collections from 'typescript-collections';

// the next line will produce an error
let foo: Collections.Set<string> = new Collections.Set<string>();
foo.add("element");
console.log(foo);

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "strict": true,
  }
}

webpack.config.js

module.exports = {
  target: "node",
  entry: "./src/main.ts",
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
    ],
  },
};

As long as I have target: "node" in webpack, which I need for other reasons, I get the following error. I assume that this has something to do with the way this package is importing modules (see https://stackoverflow.com/questions/40294870/module-exports-vs-export-default-in-node-js-and-es6). However, I have to admit that I am rather clueless about these internals and I still don't understand if my tsconfig.json or webpack.config.js is wrong, or this package requires a different importing strategy?

Could you help me resolve getting to run typescript-collections with the above configuration, while still using target: "node"?

TypeError: n(...).Set is not a constructor
    at C:\Users\mario\Desktop\typscript-collections-webpack\dist\main.js:1:30316
    at C:\Users\mario\Desktop\typscript-collections-webpack\dist\main.js:1:30365
    at Object.<anonymous> (C:\Users\mario\Desktop\typscript-collections-webpack\dist\main.js:1:30369)
    at Module._compile (internal/modules/cjs/loader.js:1200:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
blu3r4y commented 4 years ago

I found a solution: Specify the full path in the import statement.

import Set from 'typescript-collections/dist/lib/Set';
andrewplu commented 6 months ago

This issue was open 4 years ago - and still relevant...