Scenario : I've been working on a small library (let's call it myLibrary) using TypeScript and Webpack. Everything seemed to be running smoothly until I imported the library into a React application, which resulted in a crash.
On the Library Side
The main entry point (index.ts) of myLibrary has a default export structured like this :
import wrapper from "./wrapper";
export default wrapper;
Additionally, my wrapper file exposes a default export as a function (wrapper.ts) :
const create = () => {
// Some functions
return {
init,
close,
getBase,
setBase
}
}
export default create;
All unit tests for the library pass successfully.
On the React Application Side
Despite building the library without any Typescript errors, importing it into a React application led to a crash with the error message :
TypeError: myLibrary__WEBPACK_IMPORTED_MODULE_13___default(...) is not a function
The library was being called in this manner :
import createAPI from "myLibrary";
const api = createAPI(); // This line causes the crash even though it should return an object with functions
This issue is puzzling as the TypeScript compiled to JavaScript seamlessly without raising any warnings.
Details of my library's webpack configuration (4.43.0) used for building with
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" }
]
}
}
Configuration details of my library's TypeScript setup (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"]
}
I would greatly appreciate any assistance provided :)
UPDATE : Upon revising the default export to a named export :
import { createAPI } from "myLibrary";
const api = createAPI();
A new error was encountered :
TypeError: Object(...) is not a function
When attempting to console.log(typeof createAPI);
, it returned undefined, which is unexpected considering the successful tests and lack of complaints from TypeScript.