0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 = {};
});

1 Comment

This would suppose a register output format which isn't the right way to write a module as it should be loader/bundler agnostic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.