简体   繁体   English

如何在静态html文件中包含webpack块?

[英]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 我有webpack将所有单独的JS组件构建到捆绑组件中.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页面,其中包含我的components.bundle.js,但是我不知道该如何使用这些组件,因为我认为自己可以做以下事情:

<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: 运行webpack并获取bundle.js之后,您可以简单地将其添加为脚本,如下所示:

<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 . 您要执行的所有操作(例如,创建此类的实例并访问其成员)以及您希望合并到项目中的任何其他逻辑都应按照在提供的代码示例中所做的相同方式编写,也就是说,应远离包含bundle.js的实际HTML。 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 ) 并像这样访问(很可能在另一个.js文件中,例如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. 功能(可以正常工作)(不需要HTML),它必须执行所需的所有任务,而无需注入任何东西。 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. 在大多数情况下,注入HTML文件仅应在浏览器中提供此逻辑,以便能够直观地看到其效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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