Having trouble accessing functions within the webpack bundle

As someone new to the world of JS library development, I have embarked on a journey to achieve the following goals:

  1. Creating a library with TypeScript
  2. Generating a bundle using webpack5
  3. Publishing the library to npm
  4. Utilizing the library in other projects by installing the npm package

The process went smoothly until step 4, where I faced an issue upon trying to reference functions from functions.ts. Strangely enough, importing the library into script.js executed the code specified in index.ts, allowing me to see the log output. What additional steps should I take within index.ts to successfully reference functions and classes from other files like functions.ts? Keep in mind that this library will primarily be used in front-end JS files. Thank you for your assistance!

Project folder structure:

root
|-dist
|  |-library.js
|
|-scr
|  |-functions.ts
|  |-index.ts
|
|-node_modules

I aim to use index.ts as a centralized file containing references to all functions and classes without any logic.

functions.ts

export function add(x: number, y: number): number {
  return x + y;
}

export function multiply(x: number, y: number): number {
    return x * y;
}

export function subtract(x:number, y:number): number {
    return x - y;
}

index.ts

import * as func from './functions'

var f1 = func.add(2, 5);
console.log('f1 - ' + f1);

var f2 = func.subtract(6, 2);
console.log('f2 - ' + f2);

var f3 = func.multiply(10, 2);
console.log('f3 - ' + f3);

export { func }

tsconfig.json

{
    "compilerOptions": {
      "target": "es6",
      "lib": ["es6", "dom"],
      "outDir": "src",
      "sourceMap": true,
      "strict": true,
      "module": "ES2015",
      "esModuleInterop": true
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules"]
  }

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.ts',
  devtool: 'eval-source-map',
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: path.resolve(__dirname, 'node_modules'),
        include: [path.resolve(__dirname, 'src')]
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    filename: 'library.js',
    path: path.resolve(__dirname, 'dist'),
    library: 'library',
    libraryTarget: 'umd',
    umdNamedDefine: true
  },
};

New project - script.js

import * as lib from './node_modules/library/dist/library.js'

var a = lib.library.add(2, 9); // -- error, library is not found.
console.log(a);

Answer №1

If you're developing a umd library, keep in mind that they may not be as universally compatible as their name suggests. While you can import them and run the code, exporting might not work as expected.

To address this issue, consider using a different library type such as module (which is currently experimental and needs to be enabled - refer to the link for more information) or commonjs-static.

In addition to or instead of creating a umd bundle, you can provide webpack with an array of configuration objects to compile the code in multiple ways. You can also configure your package.json file with conditional exports for various module loaders.

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

Looking for assistance in showcasing information retrieved from an external API

I've been working with an API and managed to fetch some data successfully. However, I'm having trouble displaying the data properly in my project. Can anyone provide assistance? Below is a screenshot of the fetched data from the console along wit ...

angular 2 checkbox for selecting multiple items at once

Issue I have been searching for solutions to my problem with no luck. I have a table containing multiple rows, each row having a checkbox. I am trying to implement a "select all" and "deselect all" functionality for these checkboxes. Below is an example o ...

Is it possible to use non-numeric values as keys in a Typescript Map?

During a lesson: private items: Map<number, string> = new Map(); ... this.items[aNumber] = "hello"; Results in this error message: An element has an any type because the expression of type number cannot be used to index type Map<numbe ...

Blend the power of Dynamic classes with data binders in Vue.js

Recently, I've been working on a v-for loop in HTML that looks like this: <ul v-for="(item, index) in openweathermap.list"> <li>{{item.dt_txt}}</li> <li>{{item.weather[0].description}}</li> <li>{{item.w ...

Get started by setting up and utilizing react version 0.14.0 on your

I'm currently facing an issue in my project while using react-0.14.0. The error message I'm encountering is: Invariant Violation: ReactDOM.render(): Invalid component element. This may be caused by unintentionally loading two independent copie ...

Example of Signature in TypeScript Function Declaration

While going through this documentation, I found myself puzzled by the concept of having a parameter that can be both an object and a function in JavaScript. type DescribableFunction = { description: string; (a: any): boolean; }; function doSomething( ...

Guide on saving a PDF file after receiving a binary response using axios

Is there a way to save a PDF file from a binary response received through an axios get request? When making the request, I include the following headers: const config: AxiosRequestConfig = { headers: { Accept: 'application/pdf', respon ...

issue with implementing the chart.js npm package

Just recently, I added chart.js to my project using npm. My goal is to utilize the package for creating graphs. npm install chart.js --save After the installation, I attempted to import the module with: import chart from 'Chartjs'; However, t ...

The ES6 method of binding click handlers with parameters in React

After reading numerous articles on the usage of () => {} syntax, binding in the constructor, and binding in the props, I have come to understand that binding this can be performance-intensive. Furthermore, automatic binding with arrow functions incurs a ...

Filter that caters to specific number of properties of X

Looking to create a versatile filter function that can handle multiple criteria? Here's a snippet of the current filtering function: const filterRows = () => { items.filter((item) => { if(selectedDrinks.length > 0 && select ...

Use Jquery to add unique styles to specific words within a paragraph

I am looking to specifically style a particular word within a dynamic div for example, <div id="info">{$info}</div> prints <p>here you can get info about somnething. if you want more info about something then click here....</p> ...

Updating JavaScript alert title in Android webview: A guide for developers

I have integrated a web view in my Android application, which contains a button. When the button is clicked, it triggers a JavaScript function that displays an alert box with the title "The page at 'file://' says". I would like to customize this ...

What is the best way to organize the Firebase data that is stored under the user's unique

Hey there, I'm currently working on developing a leaderboard feature for an app. The idea is that users will be able to store their "points" in a Firebase database, linked to their unique user ID. This is how the data is structured in JSON format: ...

Error: Cannot access 'addEventListener' property of null in Chrome Extension due to TypeError

I've been working on developing a chrome extension that autofills input forms in web pages. However, I encountered an error that says "cannot read properties of null." This issue arises when I try to add an event listener to a button in my code. The f ...

Having trouble with the Jquery Slider script?

I recently integrated a slider from into my website, following the installation instructions. However, I seem to be facing some conflicts with another script that controls animated div movements on the same page. Upon loading the page, all elements of th ...

Tips for passing data to a child component from a computed property

Currently in the process of setting up a filter using vue-multiselect. Everything seems to be working fine, but there's one issue I can't seem to resolve. Upon page reload, the label (v-model) appears empty. The root cause seems to be that the v ...

displaying information in table cells with jquery

Is there a way to display a table inside a td element with an on-click function without showing all tables in the same column when the function is triggered? I want the table to be shown only for the specific td that was clicked. $(document).ready(funct ...

What causes the transformation of [{"value":"tag1"} into [object Object] when it is logged?

Currently on my node.js server, the code I'm using is as follows: var tags = [{"value":"tag1"},{"value":"tag2"}]; console.log("tags: " + tags); My expectation was to see this in the console: tags: [{"value":"tag1"},{"value":"tag2"}] However, what ...

What is the method to determine the length of a string with TypeScript?

Looking to derive the numerical length of a string: type Length = LengthOfString<"hello"> // ^? should equal 5 Feeling a bit lost on how to approach this. Any guidance on how to achieve this? (Currently diving into typescript's typ ...

The attempt to install "expo-cli" with the command "npm install -g expo-cli" was unsuccessful

Encountered an issue while trying to install expo-cli for creating android applications using npm install -g expo-cli. NPM version: 7.19.1 Node version: v15.14.0 Upon running npm install -g expo-cli, the installation failed with the following error mess ...