Context : I am building a small library (let's call it myLibrary here) using TypeScript and Webpack. I built it, imported it in a react application but the react application crash.
Library side
My main entry point (index.ts) has a default export as such :
import wrapper from "./wrapper";
export default wrapper;
And my wrapper file exposes a default export which is a function (wrapper.ts) :
const create = () => {
// Some functions
return {
init,
close,
getBase,
setBase
}
}
export default create;
The library pass all the unit tests easily.
React application side
After building and when importing my library in a React application, I have no Typescript error but my React app crashes with the following message :
TypeError: myLibrary__WEBPACK_IMPORTED_MODULE_13___default(...) is not a function
After calling my library like that :
import createAPI from "myLibrary";
const api = createAPI(); // Crash here even though I should have a nice object containing my functions
It's really strange as TS really compiled nicely to JS without any warnings.
My library wepback config (4.43.0) which I use to build with command webpack --config webpack.config.js
:
const path = require('path');
module.exports = {
mode: "production",
entry: "./src/index.ts",
output: {
filename: "index.js",
path: path.resolve(__dirname, 'dist'),
},
resolve: {
extensions: [".ts", ".js"]
},
module: {
rules: [
{ test: /.tsx?$/, loader: "ts-loader" }
]
}
}
My library TS config (3.7.3) :
{
"compilerOptions": {
"outDir": "dist",
"target": "es5",
"module": "CommonJS",
"lib": ["dom", "dom.iterable", "esnext"],
"sourceMap": true,
"allowJs": true,
"jsx": "preserve",
"declaration": true,
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true
},
"include": ["src"]
}
Any help would be greatly appreciated :)
EDIT :
After updating default export to named export :
import { createAPI } from "myLibrary";
const api = createAPI();
I got a new error
TypeError: Object(...) is not a function
And when I try to console.log(typeof createAPI);
I got an undefined, which should not be possible as my tests are passing and TS doesn't complain.