Webpack's imported module does not have a constructor function

I have developed a compact JS module that I plan to transform into an npm package, although at the moment it is only available on GitHub. This module has been built using ES6 and SCSS, making use of webpack and babel for transpilation.

To conduct its testing, I set up a separate project with a similar configuration (utilizing webpack and babel). Following the npm installation of my module, when attempting to import it into my index.js file, Chrome Developer Tools throws the following error: (where x stands for the name of my module)

index.js:11 Uncaught TypeError: x__WEBPACK_IMPORTED_MODULE_1___default.a is not a constructor
    at eval (index.js:11)
    at Object../src/index.js (main.js:368)
    at __webpack_require__ (main.js:20)
    at eval (webpack:///multi_(:8081/webpack)-dev-server/client?:2:18)
    at Object.0 (main.js:390)
    at __webpack_require__ (main.js:20)
    at main.js:69
    at main.js:72

Despite going through numerous responses and attempting various solutions, the issue remains unresolved. The setup for my module is outlined below.

.babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["ie >= 11"]
      }
    }]
  ],
  "plugins": [
    "transform-es2015-modules-commonjs",
    "transform-class-properties"
  ]
}

webpack.common.js

const path = require('path')
...

webpack.prod.js

const merge = require('webpack-merge')
...

package.json

{
  "name": "my-module-name",
  "version": "1.0.0-beta.1",
...

Any guidance or assistance would be highly valued. Should additional information be required, please do not hesitate to reach out.

Answer №1

If you're not the creator of the library and are encountering difficulties while using another library, you might come across an error message similar to this:

TypeError: [LIBRARY_NAME]__WEBPACK_IMPORTED_MODULE_3__ is not a constructor

If this scenario sounds familiar, it's possible that you're importing the library incorrectly within your code (potentially due to issues with default exports). Take a moment to review the documentation provided by the library for accurate usage instructions.

The solution could be as straightforward as making this adjustment:

import Foo from 'some-library/Foo';

to this instead:

import { Foo } from 'some-library';

Answer №2

The reason it's not functioning properly is due to the absence of libraryTarget and library properties. These properties inform webpack on the module format you want to create, such as commonjs (module.exports) or es (export).

A suggested solution would be:

...
  output: {
    path: path.join(__dirname, 'dist'),
    filename: path.join('[name]', 'index.js'),
    library: "my-library",
    libraryTarget: "umd" // exposes and determines when to utilize module.exports or exports.
  },
...

Answer №3

In addition to specifying the libraryTarget, it might also be necessary to relocate the export in the JavaScript file to the default position.

function MyClassName() {
  ...
}

export default MyClassName;

Subsequently, in the webpack configuration, you will need to define the library type as umd ...

(Please note that I am utilizing the newer library.type instead of the older libraryTarget. You can refer to https://webpack.js.org/configuration/output/#outputlibrarytarget for more information).

 const path = require('path');
 
 module.exports = {
    mode: "production",
    entry: '../wherever/MyClassName.js',
    
    output: {
        library: {
          name: "MyClassName",
          type: "umd",  // see https://webpack.js.org/configuration/output/#outputlibrarytype
          export: "default",  // see https://github.com/webpack/webpack/issues/8480
        },
        filename: 'MyClassName.min.js',
        path: path.resolve(__dirname, '../wherever/target/')
    },
    optimization: {
        minimize: true
    }
 };

By using the export default, the class becomes accessible in JavaScript as if the file was directly included, for example,

<script type="text/javascript" src="MyClassName.min.js"></script>
<script type="text/javascript">
<!--

var myInstance = new MyClassName();

// -->
</script>

Disclaimer: Despite the original question being three years old, I decided to provide this answer based on my recent experience with the "is not a constructor" issue. It took me hours of searching before discovering the solution involving default. And amazingly, this wasn't the first time I had to search for it :D

Answer №4

Refer to David Calhoun's response, in case you encounter this issue with a third-party framework, you might be attempting to bring in a CommonJS module as an ECMAScript module. The workaround suggested is to utilize the `require` function instead of `import`, for example, replacing

import { Foo } from 'bar'

with

const Foo = require('bar')

(There may be a more graceful solution for this problem, but this method was effective for me.)

Answer №5

If you are using webpack 5 and babel 7 combination

"webpack": "5.73.0",
"@babel/core": "7.4.4",
"@babel/preset-env": "7.4.4",
"babel-loader": "8.0.5",

AND wish to implement class instead of function, here's what worked for me:

class Person {
   constructor(fname, lname, age, address) {
      this.fname = fname;
      this.lname = lname;
      this.age = age;
      this.address = address;
   }

   get fullname() {
      return this.fname +"-"+this.lname;
   }
}

export default Person;

In my situation, I did not need a .babelrc file

Answer №6

The issue I encountered was within my React project when attempting to utilize the native Error constructor in JavaScript, specifically with the statement throw new Error("something").

After examining my code, it became apparent that a component named Error was present and imported into the same file as the built-in JS Error constructor. This collision of names between the component and the native constructor resulted in the error that was described.

Answer №7

In my experience, the problem was caused by a cache issue. I resolved it by clearing out cookies and cached data, then closing and reopening the browser. This solution worked for me.

Answer №8

Summary

Ensure correct importing by using index files efficiently.

Detailed Explanation

In my case, the issue stemmed from incorrect imports via index files. I had several directories each with their own index.ts files that exported all files within said directory. These index files were all gathered and re-exported through a main index.ts file to allow for centralized importing.

src/
├── index.ts
├── module1/
│   ├── index.ts
│   ├── file1.ts
│   └── file2.ts
└── module2/
    ├── index.ts
    ├── file3.ts
    └── file4.ts

One of the imports in file4.ts looked like this:

import { file1Class, file2Class, file3Class } from "src";

I later realized it needed to be split into two separate imports as follows:

import { file1Class, file2Class } from "src/module1";
import { file3Class } from "src/module2";

Answer №9

I found the solution that worked for me using

const { SubresourceIntegrityPlugin } = require('webpack-subresource-integrity');

This may be useful for anyone attempting SRI in a React application.

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

Concealing my menu with overflow-x: hidden on the body is not an option

Despite setting overflow-x: hidden on the body element, I'm still experiencing horizontal scrolling and can't seem to find a solution. I've searched online for solutions without success. That's why I'm reaching out here in hopes o ...

What is the best way to retrieve the value of a text box in VUEjs using its unique identifier?

In my form, there are a total of two text boxes with predefined values. However, I am looking for a way to retrieve the value of one specific textbox based on the entered ID number. For example, if I input "1," I expect to see the value of text box 1 only ...

challenges encountered with the clearTimeout() method in vue.js

I am currently working on implementing a shopping cart using Vue, but I am encountering some challenges. As I am new to using this library, it is possible that I am making some basic mistakes. Here is the issue I am facing: When I add an item to the cart, ...

Ways to modify the default text in a dropdown menu?

I'm currently attempting to modify the title of a dropdown using the Multi-select plugin found here. However, I've encountered an issue where I am unable to dynamically change the text (Dropdown title) of the dropdown using JavaScript. $(' ...

Using flags to translate text on Google should not result in being redirected to another website

I have integrated Google's language picker with country flags into my WordPress template using the code below: <!-- Add English to Chinese (Simplified) BETA --> <a target="_blank" rel="nofollow" onclick="window.open('http://www.google. ...

Can you explain the significance of syntax in sample code (typescript, react)?

const sampleFunction: (inputString: string) => string = inputString => { return inputString.split(""); } I'm a bit confused about the code below and would appreciate some clarification. I understand that only "string" as a type is accepted, b ...

What could be the reason why modules are not showing up in the `npm list -g --depth=0`

I have gulp and bower installed globally. Even though I have them installed, for some reason, neither of them appear in npm list. Is there something I am missing or doing wrong? nathanbrauer@macthan:~$ npm list -g --depth=0 /usr/lib ├── <a href ...

Using Vue Composition API to invoke a child component's method that employs a render function

While using Vue composition-api with Vue2, I encountered an issue when attempting to call a method of a component with a render function from its parent component. Everything works fine without the render function. TemplateComponent.vue <template> ...

Regular expressions to eliminate leading zeros from a string, excluding those that are part of decimals

Looking for a JavaScript regex that can remove any leading 0 in a string if the string is an integer. 0 => '' 0000 => '' 001 => 1 0.11 => 0.11 0000.11 => 0.11 11000 => 11000 I've been attempting to solve t ...

Having trouble switching states in React

Can anyone assist me with a code issue I'm facing when trying to run it onClick? The desired functionality is for each button to display the names set in the 'useState' state, which should then change to 'Click on close' when click ...

Adding choices to enhance dual List styling

var demo2 = $('#tree_listbox').bootstrapDualListbox({ nonSelectedListLabel: 'Non-selectedsss', selectedListLabel: 'Selected', moveOnSelect: false, }); var data = [ { "id": 194, "name": "Endüstri Mühendisliğ ...

Identify the opening of the console for the background page of a Chrome

Is it possible to detect when I click on the "Background Page" for my test plugin on the "chrome://extensions/" page? This question has been boggling my mind. Currently, whenever I open the background page, the console remains undocked. After reading a po ...

Exploring the usage of promises with data in VueJS async components

Experimenting with VueJS 2.0 RC and utilizing the fetch API to retrieve data for certain components. Here's a sample scenario: const Component = { template: '#comp', name: "some-component", data: function () { return { basic ...

What's the best way to use the like query in Mongoose?

Struggling with applying a Like query using Mongoose in the MEAN stack. Despite trying various solutions found online, nothing seems to work for me. Here is the model schema: const mongoose = require('mongoose'); const ItemTransactionSchema = ...

React Native error: encountering the error message "undefined is not an object '_this3.props.navigation()'"

I am encountering an error in the navigationOptions() function when running my React app, but everything is working correctly in the render() function. App.js import React, { Component } from 'react'; import { AppRegistry, View } from 'r ...

Create a sinusoidal wave and stream it through the web browser

I'm looking for a code snippet that can: create a sine wave (an array of samples) play the wave This should all be accomplished in a web browser using an HTML5 API in JavaScript. (I've tagged this with web-audio, but I'm not entirely ...

Enhance event handling in Google Maps JS API v3 by setting priorities on event listeners

Is there a way to subtly prioritize event listeners without changing the order they were added in? See code snippet: var listener1 = function () { console.log('@listener1'); }, listener2 = function () { console.log(' ...

Encountering an error during ng build -prod with Angular 9, as the css-loader module cannot be located

My package.json configuration looks like this: "dependencies": { "@angular/common": "2.2.1", "@angular/compiler": "2.2.1", ... }, "devDependencies": { "@types/jasmine": "^2.2.30", "angular-cli": "1.0.0-beta.21", ... I was successfully running ng buil ...

Getting the click event object data from a dynamically created button with jQuery or JavaScript

I have a task of tracking page button click events. Typically, I track the objects from statically created DOM elements using: $('input[type=button]').each(function () { $(this).bind('click', function () { ...

The `command prompt` does not acknowledge Ionic

After installing Ionic version 2 using the command npm install -g ionic@alpha, I encountered an issue where the ionic command was not functioning properly. You can see the installation process here. If you are facing a similar issue, please refer to this ...