首页 > 解决方案 > 重构 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>

标签: javascriptnode.jsnode-modulescommonjs

解决方案


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 。


推荐阅读