Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use moment-timezone in Angular2 via SystemJs

I'm using Angular2 via angular2-seed (which uses SystemJS) and trying to load moment-timezone and use moment.tz.guess() specifically.

I import via:

import * as moment from 'moment-timezone';

When I do this I get the following error in my browser:

GET /node_modules/moment-timezone/data/packed/latest.json.js 404 (Not Found)

anuglar2-seed uses defaultJSExtensions which I think is why the incorrect .js is being added, so I figured I could just turn this off for moment-timezone in tools/config/project.config.ts like so:

this.SYSTEM_BUILDER_CONFIG.packages['moment-timezone'] = {
  defaultExtension: false

//I have also tried:
      map: {
        '/node_modules/moment-timezone/data/packed/latest.json.js': '/node_modules/moment-timezone/data/packed/latest.json',
        '/node_modules/moment-timezone/data/packed/latest.json': '/node_modules/moment-timezone/data/packed/latest.json'
      }
};

However, this is not working. What am I doing wrong?

like image 470
rynop Avatar asked Oct 04 '16 04:10

rynop


1 Answers

The problem is, unless you tell SystemJS that you want to use the moment-timezone-with-data-2010-2020.min.js file it will by default load moment/index.js which does a require of the tz data.

Here are the steps to configure and use correctly:

npm install moment moment-timezone --save and npm install @types/moment @types/moment-timezone --save-dev

In my component I do import * as moment from 'moment-timezone';.

You configure SystemJS like:

...
packages: {
      'moment-timezone': {
        main: 'builds/moment-timezone-with-data-2010-2020.min.js',
        defaultExtension: 'js'
      }
    }

You can then use console.log(moment.tz.guess());

For angular2-seed you do this:

project.config.ts:

...
 constructor() {

    this.NPM_DEPENDENCIES = [
      ...this.NPM_DEPENDENCIES,
      {src: 'moment', inject: 'libs'},
      {src: 'moment-timezone/builds/moment-timezone-with-data-2010-2020.min.js', inject: 'libs'},
    ];

...
    const mtzc = {
      main: 'builds/moment-timezone-with-data-2010-2020.min.js',
      defaultExtension: 'js'
    };

    this.SYSTEM_BUILDER_CONFIG.packages['moment-timezone'] = mtzc;
    this.SYSTEM_CONFIG_DEV.packages['moment-timezone'] = mtzc;
  }
like image 167
rynop Avatar answered Sep 24 '22 21:09

rynop