如何使用webpack导出功能 [英] how to export function with webpack

查看:97
本文介绍了如何使用webpack导出功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I intend to bundle all my .js using webpack. I tried with a very simple example as following.

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

Function to bundle in a test.js file :

function test() {
  console.log('hello');
}

Webpack配置:

Webpack configuration :

module.exports = [{
  {
    output: {
      filename: 'test.js',
      path: __dirname + '/public/javascript/dist'
    },
    entry: [
      './public/javascript/test.js'
    ]
  }
]

要测试的代码:

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

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

<script type="text/javascript">

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

</body>
</html>

但是我收到以下错误:Uncaught ReferenceError:test not defined。

But I receive the following error : Uncaught ReferenceError: test is not defined.

问题:为什么?

回复是:导出丢失。
多亏了这个,我更新如下:

Reponse is : "export" is missing. Thanks to that, I updated as following:

出口代码:

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

  Test.prototype.toto = function()
  {
    console.log('hello')
  }
}

Webpack conf:

Webpack conf :

{
output: {
  filename: 'test.js',
  path: __dirname + '/public/javascript/dist',
  library: 'test',
  libraryTarget: 'window'
},
entry: [
  './public/javascript/poc/test.js'
]
}

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

To create the object, I have to do : var t = new test.Test(); It's a bit heavy... Is there a way to only have to make : var t = new Test(); ?

推荐答案


为什么?

why?

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

Because you haven't exported anything from your entry point and, by default, webpack generates output in umd format without polluting global scope.

首先必须导出函数:

export default function test() {
  console.log('hello');
}

然后在webpack配置中指定library和libraryTarget。 文档。例如:

Then specify "library" and "libraryTarget" in your webpack config. Docs. For example:

output: {
  filename: 'test.js',
  path: __dirname + '/public/javascript/dist',
  library: 'test',
  libraryTarget: 'window',
  libraryExport: 'default'
},

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

this will generate code that adds window.test = _entry_return_.default .

这篇关于如何使用webpack导出功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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