I think it would be great to directly import modules from node_modules directory without need to manually provide a declaration file for it (let us assume that declaration is provided with module itself). I guess that problem are dependencies that come with declarations (file paths could be resolved relative to the module, but that would cause duplicates and compiler can't handle that). Currently working with node modules is very inconvenient because simple install from npm repository just isn't enough and we have to manually search for declarations and provide them in our project. Let's say that our project is dependent on 10 node modules (all of them have declarations) and after a year we would like to update them. We would have to manually search for new declarations and let's say that we have around 20 projects like this (it would become a nightmare). Maybe there should be an option to directly import .ts file from node module?
Do you have any suggestions?
This is a re-post from CodePlex to hear your opinions ...
If you use grunt-typescript then I've got a pull request which solves this at least for me. See https://github.com/k-maru/grunt-typescript/pull/36
From the pull request README
The standard way to use npm packages is to provide a definition file that specifies the package to the typescript and import the module from there.
///<reference path="path/to/mod.d.ts" />
import mod = module('mod')
The typescript compiler will convert the import
to a nodejs require
.
var mod = require('mod')
This is pretty unwieldy as you need to know the precise path to the npm installed package and npm can put the package at pretty much any level when you are working with multiple levels of dependencies.
With the node_modules
option in the grunt config you can just
import
a npm package without need to know the exact level where the
package has been installed by npm as long as it is installed locally
and not globally.
To import
an npm module in your typescript source do
import npmModule = module('node_modules/npmModule/foo')
Mostly due to a lucky chance this works. Typescript compiler will read
the typescript definition file node_modules/npmModule/foo.d.ts
if it
is present at some point on the way towards the root and the resulting
javascript file will contain a require
for npmModule/foo
if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With