Chirag B
Chirag B

Reputation: 2126

Unable to find Class reference from Webpack bundled file

I am pretty new to webpack and frontend development.

I have a JS file which has multiple classes, this classes would be used by other JS files.

The problem is when I directly add JS file in Script tag, and check in Browser console I can retrieve Class properly, but when I run Webpack and check with the bundled code i am unable to find any reference for the class

Following is the test code snippet:

main.js

class Human1 {
    constructor(params) {
        this.name = params.name
    }

    getName(){
        console.log(`My name is ${this.name}`);
    }
}

JS file used for webpack(created new JS so as to avoid class name re declaration)

class Human2 {
    constructor(params) {
        this.name = params.name
    }

    getName(){
        console.log(`My name is ${this.name}`);
    }
}

webpackConfig.js:

const path = require('path');

module.exports = {
    entry: './human.js',
    mode: 'none',   
    target: "web",
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },
};

Index.html

<!DOCTYPE html>
<html>
<head>
    <title>titlefdf</title>
</head>
<body>
    <script type="text/javascript" src="./bundle.js"></script>
    <script type="text/javascript" src="./main.js"></script>
    <h2> Welcome </h2>
</body>
</html>

When the files are loaded in html. In the console window I get Human1 but for Human2 I get Uncaught ReferenceError: Human2 is not defined.

Any reason what am I doing wrong

Upvotes: 2

Views: 648

Answers (1)

Chirag B
Chirag B

Reputation: 2126

You can do so by exposing it as Library. Here is the reference link

Upvotes: 2

Related Questions