简体   繁体   中英

How to include a webpack chunk in a static html file?

I have webpack building all my individual JS components into a bundle components.bundle.js

An example of a component:

export class Comp1 {
  test() {
    console.log('worked');
  }
};

I then have a static html page that includes my components.bundle.js but I don't know how I can then use the components as I thought I could just do something like:

<html>
<head>
    <script type="text/javascript" src="./components.bundle.js" charset="utf-8"></script>
</head>
<body>
    <script>
        var comp1 = new Comp1();

        comp1.test();
    </script>
</body>

But this does not work, what am I missing? Thanks!

When you have run webpack and got the bundle.js you can simply add this as a script like so:

<script src="path/to/my/bundle.js"></script>

All the operations you would like to perform (like making an instance of such a class and accessing its members) and any other logic you would like to incorporate into your project should be written the same way you have done in the code example you have provided, that is, it should be kept away from the actual HTML that will include the bundle.js . You could achieve this by creating more files that will hold and reference other logic you have written.

The main point is, it is not recommended to handle business logic inside a layout page.

For instance:

Incorrect to write

export class Comp1 {
  test() {
    console.log('worked');
  }
};

And access like this

<html>
  <head>
    <script type="text/javascript" src="./components.bundle.js" 
    charset="utf-8"></script>
  </head>
  <body>
    <script>
      var comp1 = new Comp1();
      comp1.test();
    </script>
  </body>
</html>

Correct to write

  export class Comp1 {
    test() {
      console.log('worked');
    }
  };

And access like this (most probably in another .js file, say main.js )

var comp1 = require('path/to/my/component')

comp1.test()

The take-away point here is that your code must be self-contained; functional (working) on its own (without needing the HTML), it must perform all the tasks it needs to without having being injected into anything. Injecting to the HTML file should only serve to serve this logic in the browser, in most cases, to be able to visually see its effects.

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