Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing TypeScript external modules using aliases supplied through requirejs.config

Here's my folder structure:

  • app
    • app1
      • core.ts
    • app2
      • util.ts
    • packages
      • features
        • feature1
          • index.ts
    • app.ts (bootstraps the application)
    • main.ts (main entry point)
  • vendor
    • requirejs (from https://requirejs.org)
  • index.html

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Test RequireJS with TypeScript</title>
    <script src="vendor/requirejs/require.js" data-main="app/main"></script>
  </head>
 <body>


 </body>

Notice in paths, I have added an alias for feature1 as well.
main.ts

'use strict';

require.config({
  paths: {
    app1: 'app1',
    app2: 'app2',
    feature1: 'packages/features/feature1'
  },
  deps: ['app']
});

core.ts (app1)

class Core {
  name = 'Core';
}

export = Core;

util.ts (app2)

class Util {
  name = 'Util';
}

export = Util;

index.ts (feature1)

class Util {
  name = 'Util';
}

export = Util;

From app.ts, I want to refer the core.ts, util.ts and feature1's index.ts files. This is how I attempted first and worked perfectly:

/// <amd-dependency path="feature1/index" name="Feature" />
declare var Feature: any;

import Core = require('app1/core');
import MyUtil = require('app2/util/myutil');

var c = new Core();
console.log(c.name);

var util = new MyUtil();
console.log(util.name);

var f = new Feature();
console.log(f.name);

Then I tried doing the following but failed. Seems like require() only understands relative path and it doesn't understands the aliases provided through require.config(...):

import Core = require('app1/core');
import MyUtil = require('app2/util/myutil');
import Feature = require('feature1/index'); // ERROR!: Cannot find module `feature1/index`

var c = new Core();
console.log(c.name);

var util = new MyUtil();
console.log(util.name);

var f = new Feature();
console.log(f.name);

Is my understanding correct? Any best practice to refer other external modules?

like image 934
Anup Vasudeva Avatar asked Apr 15 '26 13:04

Anup Vasudeva


1 Answers

In your code :

import Feature = require('feature1/index'); // ERROR!: Cannot find module `feature1/index`

This is a compiler error (requirejs is happy with it). TypeScript doesn't understand requirejs.config at the moment, so you must use full relative paths.

PS:This will be resolved soon though, see https://github.com/Microsoft/TypeScript/issues/5039 for details.

like image 118
basarat Avatar answered Apr 18 '26 12:04

basarat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!