The function purported by WEBPACK_MODULE_13___default(...) does not exist

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.

Answer №1

To specify the library name and module type in your webpack configuration for the library:

output: {
  path: './distribution',
  filename: 'main.js',
  library: 'api-wrapper',
  libraryTarget: 'commonjs'
},

Answer №2

If you recently updated your webpack to version 5.x.x, then you may encounter an issue related to the output.library configuration.

If you have a library setting in your webpack output, try removing it as shown below:

output: {
  path: path.resolve(__dirname, 'build'),
  filename: 'painterro.commonjs2.js',
  library: 'Painterro',  // ⏪ this line might be causing the issue
  libraryTarget: 'commonjs2',
 },

You can find more detailed information on this issue in the following link: Fix _webpack_imported_module is not a function for webpack5

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered while trying to render a Threejs FBX Object - undefined 404 (Resource not found)

I am facing an issue while loading a set of .fbx objects using FBXLoader on a WebXR App. window.fbxLoader.load("/assets/modelate_FBX/Vaza%208067134/Vaza 8067134.fbx", function( object ) { const flower = this.scene.children.find(c => c.name ...

When the click event is triggered, the second function guess() does not execute

I am currently developing a number guessing application. It consists of two functions, the first one called startGame() works correctly (it receives the maximum number and then disappears by adding the hidden class). However, the second function that is ...

Is there a way to override the JSON.stringify method within the JSON class of a TypeScript project without using a custom call?

Dealing with a React Native and TypeScript app here. I keep encountering an error from Fabric every week: "JSON.stringify cannot serialize cyclic structures." The frustrating part is that the error seems to pop up randomly, without any specific scenario tr ...

Utilize Javascript to Populate Form Fields Based on "Selected Name"

I am currently facing a challenge in using javascript to automatically populate a form, specifically when it comes to setting the value for the country field. <form action="/payment" method="post" novalidate=""> <div class="input_group"> ...

Difficulties accessing MongoDb database using Node.js

Having issues when trying to read this data collection using mongoose and Node.js: I have a single JSON object within my Collection and I'm attempting to access it with the following code: materias.find().exec(function(err1,materias){ if(err ...

What methods can you use to locate the CSS selector within HTML that meets certain criteria?

Is it possible to parse a given link and find CSS selectors with attributes that partially or completely match a specific keyword? For example, if the keyword is "print," I want to identify all CSS selectors in the link containing "print" in their name, id ...

The information from the textarea and select option is not getting through to the email

Despite following suggestions, I am still unable to figure out why my form is not functioning properly. The form I have collects various information such as name, email, phone number, a select option, and a message in a textarea input. I dynamically change ...

Exploring additional parameters within express.js

I'm currently working on creating an email sender that includes all necessary components such as 'from', 'to', 'subject', 'textBody', etc. However, I am facing a challenge in setting optional parameters in expre ...

Is there a way for me to extract and showcase the initial 10 items bearing a particular class name from a different html document on my homepage?

I am looking to extract a list of movies from an HTML file titled "movies.html". The structure of the file is as follows: <div class="movie">Content 1</div> <div class="movie">Content 2</div> <div class=" ...

Using `setTimeout` in a recursive function that is nested within another function

I am attempting to use setTimeout in a recursive function call where the main function is called recursively and subfunctions are also called recursively. Below is the code I am working on: this.myArray = Array(2).fill(undefined); StartFunction(len: numb ...

The body onload function fails to run upon the page loading

I'm having trouble with my body onload function not executing. When I load the page, I want to display all records that are selected in the drop_1 dropdown and equal to ALL. I have a script that sends values q and p to getuser.php. The values sent are ...

Unable to reach 'this' within a nested function

Struggling with a coding issue for hours now and in need of some assistance. The challenge at hand involves creating an object named Rank. Rank is expected to make DB calls in mongodb to retrieve data needed to populate a matrix, followed by executing nes ...

Encountering an error when using the Vue 3 TypeScript Composition API for style binding with an asynchronous

I utilized nexttick alongside an async method to update a DOM element. However, I am encountering issues with returning the correct style type. An error message pops up stating: error TS2322: Type 'Promise<{ maxHeight: string; }>' is not ...

Can a TypeScript interface inherit from multiple other interfaces simultaneously?

Hello Angular Community, I have a question regarding nesting three interfaces within another interface. Let me explain with some code: I am attempting to integrate the IProject1, IProject2, and IProject3 interfaces into the IAdmin2 interface: Thank you ...

Toggle visibility between 2 distinct Angular components

In my application, I have a Parent component that contains two different child components: inquiryForm and inquiryResponse. In certain situations, I need to toggle the visibility of these components based on specific conditions: If a user clicks the subm ...

Creating a button in ReactJS with text displayed under an icon

Presently, I am working with a component that looks like this: https://i.stack.imgur.com/qGCwj.png This is the code for the component: import React from "react"; import {withStyles} from "material-ui/styles"; import Settings from "material-ui-icons/Setti ...

Problems encountered when trying to deploy on Firebase

I've been working on deploying my web app to Firebase, and I successfully ran the deploy script. However, when I try to access the URL, instead of seeing my app, I'm greeted with the Open Hosting Documentation page. Here is what my firebase.json ...

React app's setTimeout function fails to execute at the designated time specified

I have a function set up in my React app to handle user authentication and signup. The function is supposed to display an alert message saying "Account Created" upon successful signup, and then redirect the user to their profile page after a 1-second delay ...

Assign a value to the input field based on changes made in another input field

I am brand new to the world of JavaScript and currently grappling with setting a value in an input field based on the onchange event of another input field. Here is my code sample for input field 1: <input type='text' onchange='methodTh ...

get a duplicate of an object

Is this the proper method for creating a duplicate of an object? class ObjectWrapper { private _obj; /*** * Copy object passed as argument to this._obj */ constructor (_obj: Object) { this._obj = _obj; } /** Return copy of this._ ...