如何使用 Webpack 导出函数并在 HTML 页面中使用它?

2023-11-24

我有一个名为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文件加载完全正常。


Add a library属性到您的输出配置:

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

Then in index.js,你应该可以打电话foo()像这样:

myLibrary.foo();

为了使其发挥作用,重要的是foo()函数正在导出export function and not export default function

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Webpack 导出函数并在 HTML 页面中使用它? 的相关文章

随机推荐