Solvedangular cli Proposal: Provide a way to add externals to webpack config

The issue is that if I use global script via app[0].scripts I cannot use it again in my .ts files.

Example: if I have:

      "scripts": [
        "../node_modules/jquery/dist/jquery.js",
        "../node_modules/moment/moment.js",
        "../node_modules/fullcalendar/dist/fullcalendar.min.js"
      ],

I cannot do: import * as moment from 'moment';. If I do so, moment will become an empty object. Of course, I can use it without importing it since it is global BUT other libs that depends on moment (angular2-moment in my case) will do import * as moment from 'moment';, they will get an empty object and their code will break.
Then I cannot use this libs. (I think #1974 is related)

I cannot remove moment from scripts since I have other global scripts that depend on it (fullcalendar). Maybe there is a way to make all this scripts work without apps[0].scripts but I have not found it.

My solution is to use webpack externals https://webpack.github.io/docs/library-and-externals.html

If I add

externals: {
      'moment': 'moment'
    },

to webpack-build-common.ts it is working.

I can provide a PR adding externals from apps[0].externals to the webpack config. Is it the right solution?

13 Answers

✔️Accepted Answer

Something to experiment with (that does not require modification of the CLI itself) is to add a vendor.ts file to the first position of scripts in angular-cli.json and remove the jquery and moment lines.

Potential contents of vendor.ts:

import * as moment from 'moment';
import * as jquery from 'jquery';

window['moment'] = moment;
window['jQuery'] = window['$'] = jquery;

More Issues: