且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从外部调用webpacked代码(HTML脚本标记)

更新时间:2023-12-05 19:56:46

看来你想公开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>

检查 gist 与实际代码。


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.