Iron:Router & Dynamic Imports: How?

Hi Everynone!

How do we take advantage of the new dynamic importing in 1.5 on a more legacy iron:router/ES5 stack? I can’t seem to be getitng simple imports of moment.js to work, while I seem to be having random luck with importing larger packages globally. Can anyone answer these questions below:


Some example questions:

How do i convert something like this into dynamic imports?
(e.g. how do i dynamically import momentjs in iron:router/ES5) (the code below hasn’t been updated to do dynamic imports)

import moment from 'moment';

Template.registerHelper('convertReadableTime', function(date) {
  return moment(date).format('MMMM Do, YYYY');
});

Template.registerHelper('convertReadableTimeAgo', function(date) {
  return moment(date).fromNow();
});

On the other hand, Importing a package accessible globally seems to work…
(Not sure why this works though?)

//Trix
import('trix').then( function(Trix) {
  return Trix;
});

Cheers!

1 Like

Let’s assume file /imports/client/moment.js, with next code:

// /imports/client/moment.js
import moment from 'moment';

Template.registerHelper('convertReadableTime', function(date) {
  return moment(date).format('MMMM Do, YYYY');
});

Template.registerHelper('convertReadableTimeAgo', function(date) {
  return moment(date).fromNow();
});

Now we have to statically require it in all templates where this code is used:

<!-- /imports/client/time.html -->
<template name="time">{{convertReadableTime date}}</template>
// /imports/client/time.js
import { Template }    from 'meteor/templating';
import '/imports/client/time.html';
import '/imports/client/moment.js';

Template.time.helpers({/*...*/});

In a router you may dynamically import templates and all code its depend from.

Router.route('/', function () {
  import('/imports/client/time.js').then(() => {
    this.render('Home');
  });
});

How do we take advantage of the new dynamic importing in 1.5 on a more legacy iron:router/ES5 stack? I can’t seem to be getitng simple imports of moment.js to work, while I seem to be having random luck with importing larger packages globally

“Legacy” - is the key word. Think about to upgrade to something compatible with latest features