从外部调用 webpacked 代码(HTML 脚本标签) [英] Calling webpacked code from outside (HTML script tag)

查看:28
本文介绍了从外部调用 webpacked 代码(HTML 脚本标签)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的类(用打字稿编写)并且我将它与 webpack 捆绑到 bundle.js 中.

Suppose that I have class like this (written in typescript) and I bundle it with webpack into bundle.js.

export class EntryPoint {
    static run() {
        ...
    }
}

在我的 index.html 中,我将包含该包,但随后我也想调用该静态方法.

In my index.html I will include the bundle, but then I would also like to call that static method.

<script src="build/bundle.js"></script>
<script>
    window.onload = function() {
        EntryPoint.run();
    }
</script>

然而,EntryPoint 在这种情况下是未定义的.那么我将如何从另一个脚本调用捆绑的 javascript?

However, the EntryPoint is undefined in this case. How would I call the bundled javascript from another script then?

添加:Webpack 配置文件.

推荐答案

看来你想将 webpack bundle 作为 图书馆.您可以将 webpack 配置为在您自己的变量中的全局上下文中公开您的库,例如 EntryPoint.

It seems that you want to expose the webpack bundle as a library. You can configure webpack to expose your library in the global context within a variable of your own, like EntryPoint.

我不知道 TypeScript,所以这个例子使用了普通的 JavaScript.但这里重要的部分是 webpack 配置文件,特别是 output 部分:

I don't know TypeScript so the example uses plain JavaScript instead. But the important piece here is the webpack configuration file, and specifically the output section:

module.exports = {
  entry: './index.js',
  output: {
    path: './lib',
    filename: 'yourlib.js',
    libraryTarget: 'var',
    library: 'EntryPoint'
  }
};

index.js

module.exports = {
  run: function () {
    console.log('run from library');
  }
};

然后您将能够像您期望的那样访问您的库方法:

Then you will be able to access your library methods like you expect:

<script src="lib/yourlib.js"></script>
<script>
  window.onload = function () {
    EntryPoint.run();
  };
</script>

使用实际代码检查gist.

这篇关于从外部调用 webpacked 代码(HTML 脚本标签)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆