Guide on creating a JavaScript library similar to jQuery utilizing ES6 and webpack

Recently, I've been working on developing my own Javascript library using ES6 and Webpack. Everything seems to be functioning well for the most part, but I've hit a roadblock. When attempting to use the library as a standalone by including

<script src="bundle.js"></script>
in my HTML page and trying to access the MyLibrary variable, I keep encountering a ReferenceError.

I'm seeking advice or guidance on how to properly set up and compile the code so that it can run without the need for require.js or other dependencies. Any help would be greatly appreciated!

Answer №1

Your inquiry seems to revolve around the process of transforming TypeScript code into a library that can be imported into HTML and used within <script>..</script> tags.

If this is indeed your focus, you can follow the basic setup provided below to kickstart your project.

package.json:

{
  "name": "qlib",
  "version": "1.0.0",
  "scripts": {
    "build": "webpack --progress --colors  --config webpack.config.js",
    "start": "webpack-dev-server --content-base ./ "
  },
  "license": "ISC",
  "devDependencies": {
    "ts-loader": "^4.1.0",
    "typescript": "^2.7.2",
    "webpack": "^4.1.1",
    "webpack-cli": "^2.0.12",
    "webpack-dev-server": "^3.1.1"
  }
}

tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "moduleResolution": "node",
        "target": "es6",
        "noImplicitAny": false,
        "lib": [
            "es6",
            "dom"
        ]
    }
}

webpack.config.js:

var webpack = require("webpack");

module.exports = {
    entry: './main.ts',

    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: ['ts-loader'], 
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        extensions: [".ts", ".js"],
    },
    output: {
        filename: 'bundle.js',
        libraryExport: 'default',
        library: 'qlib'
    }
};

main.ts: (the library entry point)

export class QLib {

    public helloWorld() {
        console.log("hello world");
    }
}

var QInstance = new QLib();
export default QInstance;

index.html:

<html lang="en" >
    <head>
        <meta charset="utf-8">
        <title>MyLib Testing </title>
    </head>
    <body>    
        <script src="dist/bundle.js" type="text/javascript"></script>   
        <script>
            qlib.helloWorld();
        </script>
        <p>testing</p> 
    </body>
</html>

Finally, install, build, and start your project using the following commands:

npm install && npm run build && npm start

Answer №2

If you want to create your own JavaScript library, simply create a new JavaScript file and include it in your project as you normally would. It's possible that the problem arises when you try to reference the MyLibrary variable. Make sure you are not referencing the variable before your JavaScript file has finished loading.

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

Manipulating nested arrays using index values in JavaScript

Can someone assist me in sorting a multidimensional array based on the value of the first index? I've tried using a for loop without success. Looking for solutions in JS or jQuery. I want to convert the following array: var pinData = [ ['< ...

Scrolling to the active list item in the navigation bar

Having an unordered list with the id mainul in the navigation bar is causing a problem when the page reloads. The navigation bar always starts at the beginning, but I would like it to automatically scroll to the active li element. This is my HTML code: & ...

Using JavaScript regex to eliminate content enclosed in parentheses, brackets, and Cyrillic characters

Is there a way to transform (Test 1 / Test 2) [Test 3] Отдел / Here is title - subtitle (by Author) - 1234 (5678-9999), descriptions (best), more descriptions into Here is title - subtitle (1234) (descriptions) using a combination of JavaScript an ...

Having trouble retrieving the header with axios.create?

In my axios.js file, I set up an axios instance as shown below: const instance = axios.create({ baseURL: "url", timeout: 5000, headers: { authorization: "key", }, }); export default instance; I am using this instance ...

asp gridview Export

I have a javascript function below that is currently functioning. I made a modification to the code (from examples found online): WinPrint.document.write(printContent.outerHTML); Initially, I used innerhtml but the grid formatting was not correct. Howeve ...

Reorganizing data with JSON using JavaScript

I have a JSON data that I am parsing with NodeJS and I need to restructure it into a different JSON format. The original JSON includes multiple "pages" objects within the "rows" object, each containing similar keys and values except for the "values" and "d ...

The nodejs on localhost seems to be lost in the digital void with

Currently, I am working on a Node.js Express application to retrieve data for a web page. However, an error message stating '404 Not Found' appears when trying to open the webpage. When inspecting the browser's DevTools, the following error ...

What is the reason behind the improved performance I experience in Chrome with the Developer Console open?

Currently, I am developing a small canvas game completely from scratch using pure JavaScript. This game utilizes a 2D lighting algorithm that is akin to the one found here. It features only one light source and 25 polygons, resulting in approximately 30,0 ...

Tips for invoking an external JavaScript function using AJAX

I find myself a bit confused. In my project, there is an external javascript file called Hierarchy.js located in the Scripts folder. This file contains several functions, one of which is KeySelected. I need to call this function in the OnClientItemSelected ...

Issue with using GET fetch request in JavaScript-ReactJS app

I'm currently attempting to make a basic GET request from my ReactJS application to a Node.js API. However, I am encountering a 304 status response instead of the desired 200 status. My goal is to store the response from the GET request in a variable. ...

Lack of data in the request body of a Node.js

I'm a beginner with node.js and I've run into an issue trying to send data from the client to the server. Below is the code on the client side: var roomName = document.indexform.room[1].value; const roomInfo = { value: `${roomName}`, text: `${roo ...

Showing changes in state in real-time using ReactJS: A quick guide

Hello, I am currently facing an issue while trying to add a comment and display it immediately on the DOM. Whenever I type any word in the form box, it does not appear in the box. Additionally, pressing the enter key does not trigger a POST request. Could ...

The functionality to display dynamic images in Vue.js appears to be malfunctioning

As a newcomer to vue.js, I am facing a challenge in dynamically displaying images. Manually changing the images works fine, but I'm running into issues with dynamic display. I've come across similar problems online, but none of the solutions seem ...

Updating a JSON property in JavaScript on the fly

I am looking to dynamically replace the content of "placeholder" with {"John": "Dough"} using a function call. This initial method seems to work fine: a = {foo:{bar:{baz:"placeholder"}}}; a.foo.bar.baz = {"John" : "Dough"}; console.log(JSON.stringify(a)) ...

Creating a method for a Discord Bot to communicate through a Webhook (loop)

I am looking to enhance my bot's functionality by implementing a webhook triggered by a specific command. Once activated, the webhook should send a message at regular intervals. The idea is to obtain the token and ID of the created webhook, and then ...

Alignment of tooltips in Javascript map visualizations

After a developer backed out of my project near the 95% completion mark, I have been working tirelessly to finish it on my own. My current focus is on adjusting the tooltip placement for the map featured on this page: Visit here for context You can view ...

What is the most effective method for displaying two external web pages next to each other?

Looking for a solution to display an English Wikipedia article on the left side of the page alongside its Spanish version on the right side. Wondering if it's possible using HTML, JavaScript, AJAX, etc. I am aware that I could use iframes, but I woul ...

bespoke numerical values within the Ionic 2 spectrum

The usual ionic range has a set minimum and maximum value for the possible range of values. <ion-range min="1" max="20" ...> However, I am in need of a custom range where the slider should only allow these specific values: {1, 5, 7, 20}. Is there ...

What methods are commonly used to calculate the bitsPerSecond rate for media recording?

Is there a specific formula that combines frames per second and resolution to determine the bits per second for video encoding? I'm struggling to figure out the appropriate values to use for specifying the bits per second for 720p, 1080p, and 4k video ...

Inspecting every element within an array and indicating a negative outcome if any item is not a string

I'm currently working on a function called 'every' that takes in an array and a callback function as arguments. The purpose of the callback function is to determine if all elements in the array meet a certain condition. In my case, I want th ...