ClickThisNick
ClickThisNick

Reputation: 5250

Angular 2 System Config Paths Importing Custom Javascript Modules

How do I import javascript files as modules in Angular 2?

Right now in my system config I have:

System.config({
  paths: {
    lodash: '../../node_modules/lodash/index.js',
    constants: 'app/constants.js'
},

I have a file constants.js which is:

import {Injectable} from 'angular2/core';

@Injectable()
export class Constants{
  api_dir: string;

  constructor(){
      var prod = false;

      if (prod){
          this.root_dir = 'http://google.com/'
      } else{
          this.root_dir = 'http://localhost/'
      }
      this.api_dir = this.root_dir + 'api/'
    }
  }

In one of my components I have:

import {Constants} from 'constants';

Which gives me the error:

Cannot find module 'constants'

How do I turn a javascript file into a module so I can always import it without giving the relative path to it?

Upvotes: 0

Views: 911

Answers (2)

Ludohen
Ludohen

Reputation: 8555

If you're using typescript you would have to declare your module in a .d.ts file first. I supposed the error you're getting is a compiler one, not a runtime one.

// ./constants.d.ts
declare module "constants" {
  // ... export whatever
  export interface IConstant {
    root_dir: string;
    api_dir: string;
  }
}

Otherwise your System config looks OK. If you want to avoid writing file extension everywhere, you can use defaultJSExtensions = true config option.

Upvotes: 1

Thierry Templier
Thierry Templier

Reputation: 202206

I think that you should use explictly SystemJS API to register your module. Something like that, in your app/constants.js file:

System.register([], true, function(require, exports, module) {
  exports.Constants = {};
});

Upvotes: 0

Related Questions