如何使用webpack导出功能

MrF*_*Flo 10 javascript webpack

我打算用webpack捆绑所有的.js.我试着用一个非常简单的例子如下.

要在test.js文件中捆绑的函数:

function test() {
  console.log('hello');
}
Run Code Online (Sandbox Code Playgroud)

Webpack配置:

module.exports = [{
  {
    output: {
      filename: 'test.js',
      path: __dirname + '/public/javascript/dist'
    },
    entry: [
      './public/javascript/test.js'
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

要测试的代码:

<html>
<head></head>
<body>

    <script src="./javascript/dist/test.js"></script>

<script type="text/javascript">

window.onload = function()
{
    test();
}

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:未捕获的ReferenceError:未定义测试.

问题:为什么?

[编辑]回复是:"导出"丢失.多亏了这一点,我更新如下:

出口代码:

export function Test() {
  this.t = 1;

  Test.prototype.toto = function()
  {
    console.log('hello')
  }
}
Run Code Online (Sandbox Code Playgroud)

Webpack conf:

{
output: {
  filename: 'test.js',
  path: __dirname + '/public/javascript/dist',
  library: 'test',
  libraryTarget: 'window'
},
entry: [
  './public/javascript/poc/test.js'
]
}
Run Code Online (Sandbox Code Playgroud)

要创建对象,我必须这样做:var t = new test.Test(); 它有点沉重......有没有办法只需要制作:var t = new Test(); ?

Yur*_*nko 15

为什么?

因为您没有从入口点导出任何内容,并且默认情况下,webpack以umd格式生成输出而不会污染全局范围.

首先必须导出您的功能:

export default function test() {
  console.log('hello');
}
Run Code Online (Sandbox Code Playgroud)

然后在webpack配置中指定"library"和"libraryTarget".文件.例如:

output: {
  filename: 'test.js',
  path: __dirname + '/public/javascript/dist',
  library: 'test',
  libraryTarget: 'window',
  libraryExport: 'default'
},
Run Code Online (Sandbox Code Playgroud)

这将生成添加的代码window.test = _entry_return_.default.