javascript - 重构 nodejs 模块
问题描述
我正在使用 Laravel Mix 来编译节点模块。
在app.js
我加载了以下模块。
window.Helper = require('./Helper.js');
require('./Calendar.js');
这Helper.js
module.exports = {
foo: function(){
console.log('foo called!');
},
bar: function () {
console.log('bar called!');
}
}
在视图中,我可以通过简单地从 Helper 模块运行函数:-
<script>
Helper.foo();
Helper.bar();
</script>
但是,我无法重构Calendar.js
在每个页面上运行的文件。
import { Calendar } from '@fullcalendar/core';
import interactionPlugin from '@fullcalendar/interaction';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
document.addEventListener('DOMContentLoaded', function() {
var calendarElement = document.getElementById('calendar');
var calendar = new Calendar(calendarElement, {
plugins: [ interactionPlugin, dayGridPlugin, timeGridPlugin ],
initialView: 'dayGridMonth',
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
firstDay: 1,
editable: false,
droppable: false,
allDaySlot: false,
displayEventTime: true,
defaultTimedEventDuration: '00:10:00',
slotDuration: '00:10:00',
snapDuration: '00:10:00',
forceEventDuration: true,
slotMinTime: '08:00:00',
slotMaxTime: '20:00:00',
});
calendar.render();
});
如何重构代码,以便可以像 Helper 模块一样加载日历模块。
例子:-
app.js
window.Helper = require('./Helper.js');
window.Calendar = require('./Calendar.js');
在视图中我可以像
<script>
Calendar.init('#calendar');
Calendar.run();
</script>
解决方案
在Helper.js
中,您已经指定了模块导出的内容。在这种情况下,您使用 Node 的 CommonJS 模块语法来指定导出的数据,方法是将其分配给module.exports
. 您可以在 Node 文档中阅读更多相关信息:https ://nodejs.org/docs/latest/api/modules.html 。
在 的情况下Calendar.js
,您没有指定任何导出。因此,当您需要它时,代码会运行,但该模块不会返回任何内容。
在Calendar.js
中,由于您使用的是 ES 模块语法,因此您可以像这样指定导出:
export function init() {
/* do things */
}
export function run() {
/* do other things */
}
现在,当您使用require
它时,可以在以下位置导入(分配和使用)这些方法app.js
:
window.Calendar = require('./Calendar.js');
您可以在此处阅读有关 ES 模块的更多信息:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules 。
推荐阅读
- python - Flask 多线程
- java - P2P网络和序列化
- xml - Spring - bean 初始化参数 - UnsatisfiedDependencyException - 无法将 DataBean 转换为 Vector?
- sql-server - 具有高级服务的 SQL Server Express
- android - 如何确定这是新 App 发布还是旧 App?
- unix - 如何仅在第二个和倒数第二个字符相同的文件中打印行?
- javascript - 页面对象方法?
- java - 如何在不禁用其他功能的情况下禁用 TLS_RSA_WITH_AES_128_CBC_SHA?
- javascript - 赛普拉斯 IO- 编写 For 循环
- javascript - 匹配以特殊字符开头或结尾的整个单词