简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM