javascript - 如何使用 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
文件加载正常。
解决方案
在输出配置中添加一个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
推荐阅读
- bash - 如何从具有 bash 文件名的列表中读取全局变量?
- azure-devops - Azure DevOps 2019 为什么我们的 Burndown 图表中没有跟踪故事点
- python - 按位或“|” 与 Python 中两个的正幂的加法“+”
- node.js - 如何使用自定义 url 和文件夹将图像上传到 cloudinary
- excel - 与包含/排除匹配的复杂查找
- python - “关闭和停止”功能在 macOs High Sierra 上的 Canopy 下启动的 jupyter 笔记本中不起作用
- python - psutil.cpu_times() 返回的时间“单位”是多少?
- javascript - 查找未销毁的 Vue 组件
- neo4j - 如何激活 algo.asNode() 函数是 neo4j?
- javascript - 标签不活动时 Chrome 扩展程序代码不再运行?