0

I am currently working on a Node.JS project written in TypeScript using Node.JS Tools for Visual Studio (NTVS). I have a few classes and enums spread out in 3 or 4 files in my project. I am now trying to use the classes defined in those files from my main app file. From my previous work with Node, I know that I would normally need a require call to import each other file/class if I were working with a text editor and the command-line compiler. But, if I open any TypeScript file in my project and start typing the name of a class defined in a different file, Visual Studio shows IntelliSense autocomplete for the class name and its members. This makes me think that the NTVS and/or TypeScript configuration are automatically making all of my classes available project-wide. But if I click the 'run' button, errors are printed to the console because Node can't find the referenced classes at runtime.

This behavior leads me to believe that IntelliSense isn't actually telling me that the classes are available, just that they exist (which seems odd). If I add a require call to the top of the file, and use that imported value instead of the original class name, Node finds the class and I can use it in my code. But this presents two problems:

  • I must come up with a new name to use for the variable that I import the class into. If I require() it with the original name, Visual Studio shows errors saying that the identifier is a duplicate, because it seems to believe that the original class is available project-wide.
  • I don't get the autocomplete or type checking in my usage of the class. This pretty much defeats the purpose of using TypeScript.

So, what's the proper way to do this import? Is there a way to make all my classes available globally? If not, what import statements do I need?

Wasabi Fan
  • 1,763
  • 3
  • 22
  • 36

1 Answers1

1

This behavior leads me to believe that IntelliSense isn't actually telling me that the classes are available, just that they exist

unless you have top level import or export statement the file is considered a global module and is available project wide : http://basarat.gitbooks.io/typescript/content/docs/project/modules.html A global module will not work at runtime in node.js

You should use file level modules using import/export and compile with --module commonjs

basarat
  • 261,912
  • 58
  • 460
  • 511
  • If I export all of my classes and then import them like this: `var TestClass = require('test-class.js').TestClass;`, I lose the IntelliSense because I'm getting it from an import, which Visual Studio can't trace. My question is mainly regarding importing the classes while preserving IntelliSense and debugging capabilities. – Wasabi Fan Jul 11 '15 at 05:22
  • Never mind -- I figured it out! I had been using `var` for my imports instead of `import` as you had recommended. It seems to work now -- thanks! – Wasabi Fan Jul 11 '15 at 05:29