Learn how to utilize webpack for bundling a TypeScript library into a JavaScript script

Recently, I created a TypeScript library that I am currently using as an npm package. Here's a snippet of what it looks like:

index.ts

import * as peselManager from './pesel';

/**
 * Checks if a given PESEL number is valid.
 *
 * @param {string} pesel
 * @returns {boolean}
 */
export const isValidPesel = (pesel: string): boolean => {
    return peselManager.isValid(pesel);
};

While everything seems to be working fine, I also wanted to make my library available as a JavaScript script. To achieve this, I turned to webpack and set up the following configuration:

var path = require('path');
var UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
    entry: "./lib/index.ts",
    output: {
        filename: "peseljs.min.js",
        path: path.resolve(__dirname, 'dist')
    },
    resolve: {
        extensions: [".ts", ".js"]
    },
    module: {
        loaders: [{ test: /\.ts$/, loader: "ts-loader" }]
    },
    plugins: [
        new UglifyJSPlugin()
    ]
};

After running the webpack command, I successfully obtained a minified JavaScript script. However, when I tried to include this script in an example page like so:

<html lang="en">
<head>
    <meta charset="utf-8">

    <title>PeselJS Example</title>
    <meta name="description" content="PeselJS Example Page">
    <meta name="author" content="jaroslawkrol">

    <script type="text/javascript" src="peseljs.min.js"></script>
</head>

<body>
    <span id="some-span">ABC</span>
<script>
    var isValid = isValidPesel("22032101355");
    if(isValid) {
        console.log("valid");
    } else {
        console.log("invalid");
    }
</script>

</body>
</html>

I encountered an error stating

Uncaught ReferenceError: isValidPesel is not defined
. This leads me to the question: Is there a way to bundle my library for function calls like this? Am I approaching this process incorrectly? I would appreciate any feedback or suggestions on how to proceed.

Answer №1

When attempting to utilize your exported function, it may seem like it is attached to the global scope. However, with webpack's default settings, your code will be enclosed within closures that are inaccessible to the global scope unless you specifically configure webpack to expose your top-level exports.

To achieve this, make use of the library configuration option outlined in https://webpack.js.org/configuration/output/#output-library

output: {
    filename: "peseljs.min.js",
    path: path.resolve(__dirname, 'dist'),
    library: 'myLibraryName'
}

This setup will link the entry module to a variable (which will be available wherever the webpack library is loaded - such as in the window scope), allowing access to anything exported from your entry file and enabling calls to your function via this variable.

const isValid = myLibraryName.isValidPesel("22032101355")

If you require more specific control over the scope in which this library variable resides, there are additional options available for configuring the library placement, detailed here: https://webpack.js.org/configuration/output/#output-librarytarget

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

Combining multiple Vue components into a single package or file

If I wanted to create a UI Package, is there a way to consolidate multiple components into one JS file? Usually, each component would be stored in different files like this: import ButtonText from '../ButtonText.vue' import ButtonIcon from &apos ...

Remove elements generated by the .after method with Jquery

In my HTML file, I have a table with hard-coded column headers: <table id="debugger-table"> <tr> <th>Attribute</th> <th>Computed</th> <th>Correct</th> </tr> </table&g ...

JavaScript query-string encoding

Can someone clarify why encodeURI and encodeURIComponent encode spaces as hex values, while other encodings use the plus sign? I must be overlooking something. Appreciate any insights! ...

What is the most effective approach for managing exceptions at a global level in Node.js using Express 4?

Is there an Exception filter available in node.js with express 4, similar to the one in asp.net MVC? I have searched through various articles but haven't found a solution that meets my requirements. I also attempted the following in app.js: process ...

How to Force a jQuery Redraw Following Data Retrieval Using Ajax

Hey everyone, It's been a long time since I started listening, but this is my first post... I have a client who needs a complex feature on their website. They want to merge the content of 3 different pages into one seamless experience for users afte ...

Collecting user data input when a button is clicked

I am a beginner in the world of Angular and currently working on developing a simple to-do list application. My goal is to store the description, start time, and end time input by the user as an object in an array when the user clicks a button. Initially, ...

Flipping the order of elements in an array using JavaScript as described in the

While I am aware there are simpler methods to reverse arrays in JavaScript, I am seeking assistance to fully understand how this particular reverse method works. Your help in clarifying this is greatly appreciated. function reverseArrayInPlace(array) ...

Oops! There was an issue with the form field - make sure to include a MatFormFieldControl for proper validation on the

I am working on an Angular application that utilizes Angular Material components. Despite conducting extensive research online, I have not been able to find a suitable solution to the specific error message I have encountered. The issue revolves around a ...

Tips for handling an InvalidSelectorException in Selenium when logging into a website

I've been working on automating website logins using Selenium and here is the code I have written: from selenium import webdriver driver = webdriver.Chrome() driver.get("https://abcde.com") assert "xxx" in driver.title user = driver.find_element_by ...

Issue: ASSERTION ERROR: token must be declared [Expecting => null is not undefined <=Actual]

I encountered an error while working on my project. The only special thing I did was use oidc(openId) for authentication. I made some changes to the bootstrap project and now the first component that is running is the home-main component, which includes t ...

Unable to submit form upon clicking radio button in .NET Core

Trying to submit a form by clicking on a radio button. The JQuery code used for submitting the form: Form: @for (var item = 0; item < Model.Count(); item++) { <form id="myform" action="xx" controller="xxx" method="post"> ...

The operation of assigning the value to the property 'baseUrl' of an undefined object cannot be executed

I recently created a JavaScript client using NSWAG from an ASP .NET Rest API. However, I am encountering some errors when attempting to call an API method. The specific error message I am receiving is: TypeError: Cannot set property 'baseUrl' of ...

Making an API request in React based on user input

As a beginner, I am in the process of creating a simple weather application. However, the code below is not functioning as expected. I need assistance in getting user input and submitting it. Can someone please provide guidance? class App extends Component ...

JavaScript onClick event not functioning properly on iOS devices

I have created a code that can detect when a user clicks on a cell in a table and retrieves the background color set for that cell. Everything works perfectly on my desktop computer, but when I attempt to use my iPad, it does not respond. I attempted to u ...

Creating a task list using arrays and functions

I am working on developing a to-do list using an array in JavaScript, where the functions are separated from the HTML code. I have managed to set up the HTML structure, but I am facing challenges in completing the necessary functions. Fortunately, the Even ...

Prevent Node.js Express from automatically creating sessions

When I activate the session option in express using app.use(express.session({secret: "12345"}));, a session cookie is automatically created when the user visits a page for the first time. Is there a way to turn off this automatic behavior and have more co ...

Accessing a function from a separate module in Angular 2

I am encountering an error message stating "has no exported member test" when trying to import test from ConfigAppProviderModule. Could there be a mistake in how I am writing the service with config in the module? import { NgModule ,InjectionToken,Injec ...

Typescript's spellbinding courses

I'm encountering some issues with Typescript and the "@botstan/Magic" library in nodejs. Before we proceed, please take a look at the "Magic" documentation. Follow these lines: import Magic from "@botstan/magic"; import * as _ from "lodash"; @ ...

Is HTML-React-Parser giving back an object instead of a string?

Currently, I am attempting to convert basic HTML code into JSX format using HTML-React-Parser. To achieve this, I have included the script in my HTML document as shown below: <script src="https://unpkg.com/html-react-parser@latest/dist/html-react- ...

Exploring the possibilities of integrating JavaScript with Flash technology

Currently, there is a simple Flash project in development that connects to an RTMP server and streams video and audio from a webcam. The project allows users to create a stream with a specific name. This project also features an input for entering a strea ...