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

问题描述

假设我有这样的类(用typescript写的),我把它与webpack捆绑在 bundle.js 中。

 导出类EntryPoint {
static run(){
...
}
}

在我的index.html中,我将包含这个包,但是我还想调用这个静态方法。

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

但是, EntryPoint 在此处未定义案件。那么我怎样才能从另一个脚本调用捆绑的JavaScript呢?



新增:。

解决方案

看来你想公开webpack软件包作为。您可以配置webpack以将您的库展示在您自己的变量中的全局上下文中,如 EntryPoint



我不知道TypeScript,所以这个例子使用普通的JavaScript代替。但这里最重要的部分是webpack配置文件,特别是输出部分: b
$ b

webpack.config.js



  module.exports = {
条目:'./index.js',
输出:{
path:'./lib',
filename:'yourlib.js',
libraryTarget:'var',
library:'EntryPoint'
}
};



index.js



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

然后,您将可以像访问期望的那样访问您的库方法:

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

检查与实际代码。


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

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

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>

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

Added: Webpack config file.

解决方案

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.

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:

webpack.config.js

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>

Check the gist with the actual code.

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

10-28 05:09