Noor Fathima
Noor Fathima

Reputation: 67

How access webpack imported es6 class in html?

Hi I'm new to webpack and ES6, Trying to access imported class in html. i have a index.js imported classes in it.

import one from './src/one.js';
import two from './src/two.js';
import three from './src/three.js';

export {
    one,
    two,
    three
}

in index.html i'm trying to access the class.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="bundle.js"></script>
</head>
<body>
<script>
    let oneObj = new one();
</script>
</body>
</html>

Getting error "one is not defined". Please help me how can i access the classes in html.

Upvotes: 2

Views: 1180

Answers (2)

matias.g.rodriguez
matias.g.rodriguez

Reputation: 849

There are ways to do this configuring webpack (ex: https://stackoverflow.com/a/34361312/2043830) but I was unable to make it work.

So instead I use the global window object to store the things that I want to expose to index.html.

For example, in your index.js you could do:

window.exported = {one, two, three};
//or window.one = one; window.two = two ... etc

Then in your index.html:

<script>
let oneObj = new window.exported.one();
//or let oneObj = new window.one(); ... etc
</script>

I hope this helps.

Upvotes: 1

simon04
simon04

Reputation: 3312

This is not an intended use case and therefore requires special handling using expose-loader.


The idea of a module bundler is to run all JavaScript through it (other than having some code somewhere outside). So when you code with export {one, two, three} is in lib.js, use it in app.js:

import {one} from './lib.js';
let oneObj = new one();

Configure webpack to use ./app.js as entry file, and finally remove the inline script from your index.html.

Upvotes: 0

Related Questions