webpack编译后无法访问变量

Det*_*yer 4 javascript webpack

webpack编译后我无法访问变量.我需要它,因为我正在使用这个变量在onclick中调用函数.

代码就像

function DetailClass() {
  this.add = function() {
    console.log(1);
    }
}

var Detail = new DetailClass();
Run Code Online (Sandbox Code Playgroud)

Webpack将此代码包含到eval()中

在HTML中,我称之为

<div onclick="Detail.add();">Add</div>
Run Code Online (Sandbox Code Playgroud)

DDR*_*one 6

在您的webpack配置中,您必须指定output.libraryoutput.libraryTarget.

这是一个指南:https://webpack.github.io/docs/configuration.html#output-library

对于以下配置:

...
output:{
  ...
  library: 'MyLib',
  libraryTarget: 'var'
}
...
Run Code Online (Sandbox Code Playgroud)

您将能够像以下一样使用它:

<div onclick="MyLib.Detail.add();">Add</div>
Run Code Online (Sandbox Code Playgroud)