Using Rollup for Angular 2's AoT compiler and importing Moment.js

后端 未结 9 1763
天涯浪人
天涯浪人 2020-12-24 13:34

I\'m trying to follow the official AoT guide for Angular 2, and I\'m using Moment.js in my application. Moment.js is on my packages.json file, and I\'m using versio

9条回答
  •  太阳男子
    2020-12-24 14:06

    I was having the same problems described above.

    import * as moment from 'moment'; - worked when developing and loading via systemjs, but not during rollup.

    import moment from 'moment'; - worked in a rollup build but not during development.

    To avoid having to change code depending on build type, I just added moment as a global and created a helper function that I import everywhere I need to use it instead of importing moment.

    This means the same code works for both types of scenarios. It's not particularly pretty though, if there's a better way please let me/us know!

    Here's the helper function, added to it's own file momentLoader.ts

    import { default as mom } from 'moment';
    export default function moment(args?: any): mom.Moment {
        let m = window["moment"];
        if (!m) { 
            console.error("moment does not exist globally.");
            return undefined;
        }
        return m(args);
    }
    

    To use moment in other classes I just import the function and call it as if I'd imported moment directly:

    import moment from '../../momentLoader';

    let d = moment().utc("1995-12-25");

    let m = moment("1995-12-25");

    To get systemjs to load it as a global, I just followed these steps. http://momentjs.com/docs/#/use-it/system-js/

    In my case the moment config for systemjs looks like this:

    let meta = {
        'lib:moment/moment.js': { format: 'global' }
    };
    
    System.config({
        paths: paths,
        map: map,
        packages: packages,
        meta: meta
    });
    
    System.import('lib:moment/moment.js');
    

    For the rollup build you'll have to make sure moment.js is added to the page somewhere via a script tag, as it won't get included in the rollup build file unfortunately.

提交回复
热议问题