r4ph43l r4ph43l - 4 months ago 30
TypeScript Question

Import node module with systemJs in typescript file

So I tried to import a node module (immutablejs) into my typescript file:

/// <reference path="../node_modules/immutable/dist/immutable.d.ts" />
import { Map } from 'immutable';
var myMap = Map();


Here are my script tags in my index.html:

<script src="node_modules/systemjs/dist/system.js"></script>
<script src="node_modules/typescript/lib/typescript.js"></script>
<script>
System.config({
transpiler: 'typescript',
packages: {
src: {
defaultExtension: 'ts'
}
}
});
System
.import('src/main.ts')
.then(null, console.error.bind(console));
</script>


While intellisense is working in VS Code, my browser tells me it cannot find immutable:
system.src.js:1057 GET http://localhost:3000/immutable/ 404 (Not Found)

Importing a self-written typescript module with relative path just worked out fine..

What am I doing wrong?

Answer

Having the correct type definitions to satisfy the typescript compiler doesn't configure systemjs to know where to load the real javascript code for immutablejs.

When you use systemjs, it's your turn to configure systemjs accordingly so that it knows where to load the libraries from. If you don't do so, it will try to load the imported module as file from the server having the same name as your import. See this answer for exactly the same problem:

How to configure SystemJs for ImmutableJs to work in Angular 2 project

For more details about how you can configure systemjs, please see the docs here: https://github.com/systemjs/systemjs/blob/master/docs/config-api.md#map

You can also omit the reference path for the d.ts file when your tsconfig is setup such that it will search the node_modules automatically or by using a tool like typings to install definitions for libraries that don't provide some typings with their module. (See here: https://github.com/typings/typings - but this shouldn't be required for immutablejs).

Comments