首页 > 解决方案 > 如何使用 Webpack 导出函数并在 HTML 页面中使用?

问题描述

我有一个名为index.js

"use strict";

var $ = require("jquery");
window.jQuery = $;

export function foo() {
    console.log('hello world');
}

在同一目录中,webpack-config.js

module.exports = {
    entry: './index.js',
    output: {
        filename: './dist.js'
    },
    mode: "development"
};

最后我有一个index.html文件加载我捆绑的 JavaScript,并尝试使用导出的函数定义......

<script src="/media/js/dist/dist.js"></script>
<script type='text/javascript'>
    foo();
</script>

当我运行时webpack,我看不到输出错误。

但是当我加载我的 HTML 页面时,我看到:

(index):211 Uncaught ReferenceError: foo is not defined
   at (index):211

我究竟做错了什么?该dist.js文件加载正常。

标签: javascriptwebpack

解决方案


在输出配置中添加一个library属性:

module.exports = {
    entry: './index.js',
    output: {
        filename: './dist.js',
        library: 'myLibrary'
    },
    mode: "development"
};

然后在 中index.js,您应该可以这样调用foo()

myLibrary.foo();

为此,重要的foo()是要导出函数而export function不是导出 export default function


推荐阅读