Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  86] [ 6]  / answers: 1 / hits: 17847  / 4 Years ago, tue, july 28, 2020, 12:00:00

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.


More From » typescript

 Answers
26

In your webpack config of the library to point out library name & its module type:


output: {
path: './dist',
filename: 'index.js',
library: 'scorm-wrapper',
libraryTarget: 'umd'
},

[#50755] Sunday, July 19, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joanneamiyaa

Total Points: 532
Total Questions: 127
Total Answers: 98

Location: Guam
Member since Tue, Nov 3, 2020
4 Years ago
;