Importing a module results in receiving an empty object

I recently tried creating an npm module using Webpack and TypeScript. However, after building my package and attempting to import it, I encountered a problem where I received an empty object instead of the default exported function.

Here is a glimpse of my configuration :

Webpack.js :

const webpack = require('webpack');
const path = require('path');

const config = {
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
  module: {
    rules: [
      {
        test: /\.ts(x)?$/,
        use: ['awesome-typescript-loader'],
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            }
          },
          'postcss-loader'
        ]
      },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader']
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  }
};

module.exports = config;

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "strict": true,
    "noImplicitReturns": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es5",
    "allowJs": true
  },
  "include": ["./src/**/*"]
}

The module builds successfully, but when attempting to use the default import, it returns an empty object. I even tested with a simple example function:

const test = () => console.log('test');

export default test;

import test from 'my-module-name'; test() // test is not a function

Has anyone else faced similar issues while creating an npm module using webpack and typescript?

Appreciate any insights from the community!

Answer №1

After researching on Stack Overflow, I found a solution that suggests including

libraryTarget: "commonjs2"
in your webpack configuration.

Here is an example of how to implement it:

module.exports = {
    ...
    output: {
        path     : path.resolve(__dirname, 'dist'),
        filename : '[name].js',
        libraryTarget : 'commonjs2' // Make sure to add this line
    },
    ...
}

I have personally used this solution before and can confirm that it works with both TypeScript + Webpack setups when encountering a similar issue.

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

Tips for preventing microphone from muting when the screen is locked in an Angular PWA during voice calls

After successfully implementing a PWA in Angular with agora.io voice calling, I encountered an issue where the microphone would get muted on both iOS and Android devices when the phone was locked. Even after unlocking the phone, the microphone remained mut ...

Solving the Issue of Missing Minified Scripts in NPM Packages

When attempting to utilize the jquery-validation-unobtrusive NPM package, I encountered an issue where the minified version of the required script was not included by the package authors. It appears that they have excluded it via the files section in the p ...

What causes conflicting peer dependencies to be resolved by removing the package-lock.json and node modules file?

Background Recently, I became part of a new project where the task assigned to me was to upgrade React from version 17 to 18. Upon completing the upgrade for react, react-dom, and some other dependencies, I encountered several warnings related to conflict ...

Guide on incorporating node module for Babel through Webpack

When I execute the command npm run build I am encountering an ES6 related syntax error from Uglify, indicating that Babel may not be handling the node module (sec-to-min) properly. This is my .babelrc file: { "presets": ["es2015", "stage-0"], "plu ...

A guide to querying JSON data in a backend database with JavaScript

My backend JSON DB is hosted on http://localhost:3000/user and contains the following data: db.json { "user": [ { "id": 1, "name": "Stephen", "profile": "[Unsplash URL Placehol ...

Improving the method of retrieving RTK result within getServerSideProps

Currently, I am utilizing RTK Query to make an API call within my getServerSideProps function. While I can successfully retrieve the result using the code snippet provided below, I find the process somewhat awkward. Additionally, the result lacks proper ty ...

Obtain an array containing only one property value from an array of objects

Within my array of objects, I am looking to extract all the controls and move them to a new array: this.formModel = { sections: [ { title: 'Section 01', controls: [ new FormControlInput({ ...

The specified file ngx-extended-pdf-viewer/assets/pdf.js cannot be found

I have integrated the ngx-extended-pdf-viewer package in my Angular application using npm to enable the display of PDF content. According to the setup instructions, I have added the following configuration in my angular.json file: "assets": [ ...

Why do all the values in my table turn into input boxes when I click the edit button?

When working with my HTML, I am using ngFor to iterate through a list of items and display them in a table. However, when I try to edit an item by clicking on it, the input box opens but all the table rows display the same value. <tr *ngFor="let item o ...

Invoking a controller from another controller in the Express framework using Typescript

Currently, I am trying to call a controller from another controller in my code. While attempting to pass parameters using {params: {task_id: String(task_id), result}}, TypeScript is flagging an error indicating that res does not have all the required attri ...

Trouble configuring a React TypeScript router has arisen

Recently, I have successfully set up multiple routers in TypeScript. However, I am facing challenges in implementing the same in a new project for some unknown reason. import React from 'react'; import Container from './Components/Containers ...

Troubleshooting challenges with a React web application and resolving the issues

Recently, I stumbled upon a React web application from GitHub that caught my interest. I followed the instructions and ran the code using "npm start" in the terminal before accessing it at http://localhost:8080/webpack-dev-server/. However, I encountered a ...

Issue with blueprintjs/core type in JupyterLab Extension after running npm install

Developed a JLab extension and saved it to Git repository. Established a new environment and successfully pulled the code, which was also verified by a friend. Subsequently, included a new react object to the extension and pushed it back to Git in a fresh ...

Executing npm scripts with parameters and substituting placeholders with those parameters in the script call

I am trying to add a scripts entry in my package.json file to streamline the build process for different environments. When running the script, I want to be able to replace $1 with a parameter that I pass when executing npm run build-script, such as --env ...

The angular2 error message indicating a property cannot be read if it is

Encountering an issue trying to utilize a method within an angular2 component. Here's the code snippet : import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AgGridModule } from &ap ...

Exploring the latest upgrades in React 18 with a focus on TypeScript integration

I am currently working on a complex TypeScript project with React and recently made the decision to upgrade to the new version of React 18. After running the following commands: npm install react@18 npm install react-dom@18 npm install @types/react-dom@18 ...

Error: Unable to locate the module 'encoding' in the specified directory '/vercel/path0/node_modules/cross-fetch/node_modules/node-fetch/lib'

Has anyone encountered the warning issue related to non-breaking changes with the npm package @supabase/supabase-js? The warning message: warn - ./node_modules/cross-fetch/node_modules/node-fetch/lib/index.js Module not found: Can't resolve 'en ...

Preventing click propagation for custom react components nested within a MapContainer

I have developed a custom control React component for a map as shown below: export const MapZoom = () => { const map = useMap() const handleButtonClick = () => { map.zoomIn() } return ( <IconButton aria ...

Error event in events.js in Electron Windows Store is thrown and not handled

I am encountering errors while trying to publish my app to the Windows 10 store, and I am struggling to find solutions for them. > node build-store.js Configuration: Desktop Converter Location: false Expanded Base Image: false Publisher: ...

Retrieve the maximum value on the x-axis in Highcharts using React

I need to retrieve the maximum value of the x-axis and place an annotation at the very end: y: chart.xAxis[0].max-1 What is the correct syntax to make it work in a React application? You can view a live demo here. ...