TypeScript error in Visual Studio – Cannot find module, problem with the tsconfig.json file


As much as I like to write blogs, I also like to follow and work through other people’s blogs, especially if they are step by step instructions similar to the way I think. This one particular blog was showing how to create a simple Angular Hello World app. I followed the blog to the letter and when I tried to build the app I kept getting the following error messages

  • Experimental support for decorators is a feature that is subject to change in a future release. Set the ‘experimentalDecorators’ option to remove this warning.
  • Cannot find module ‘@angular/core’
  • Cannot compile module unless the ‘—module’ flag is provided with a valid module type. Consider setting the ‘module’ compiler option in a ‘tsconfig.json’ file.

typescripterrormessage

This makes no sense, as in my tsconfig.json file I had everything setup correctly. I had set experimentalDecorators to true, so I shouldn’t have received the first error message. Couldn’t work out why it couldn’t find @angular/core as I had used the npm package manager to install it, and in my tsconfig.json file I had set the module to ‘commonjs’. I checked on other websites that I had set up my tsconfig.json file correctly.

{
compilerOptions: {
declaration: true,
emitDecoratorMetadata: true,
experimentalDecorators: true,
lib: [
"es2015",
"dom"
],
module: "commonjs",
moduleResolution: "node",
noImplicitAny: true,
removeComments: false,
sourceMap: true,
suppressImplicitAnyIndexErrors: true,
target: "es5",
typeRoots: [
"../../node_modules/@types/"
]
},
compileOnSave: true,
exclude: [
"node_modules/*",
"**/*-aot.ts"
]
}

It seems if you download TypeScript 2.0 for Visual Studio 2015 you will not be able to use a tsconfig.json file. If you are working with CommonJS module system, Visual Studio will ignore the tsconfig.json file, even though putting the tsconfig.json file within the project, Visual Studio prevents the use of the TypeScript build section of the project properties.

typescriptdisabled

 

The tsconfig.json file is required in Visual Studio Code, but it doesn’t seem to be required for Visual Studio. To fix your error messages, first, remove the tsconfig.json file from your project. This then makes the Typescript build on the properties page enabled. I switched the Module system to CommonJS and ECMAScript version to ECMAScript 6. This got rid of my bottom two errors, however I was still getting the message:

Experimental support for decorators is a feature that is subject to change in future release. Set the ‘experimentalDecorators’ option to remove this warning.

To fix this error:

  • Unload the project from your solution – right click the project and select Unload Project
  • Once you have unloaded the project, you can right click it again, and then edit the project file.
  • Add the following to both PropertyGroup where the condition is for debug or Release. (<PropertyGroup Condition=” ‘$(Configuration)|$(Platform)’ == ‘Debug|AnyCPU’ “> or  <PropertyGroup Condition=” ‘$(Configuration)|$(Platform)’ == ‘Release|AnyCPU’ “> )
        <TypeScriptExperimentalDecorators>True</TypeScriptExperimentalDecorators>
        <TypeScriptEmitDecoratorMetadata>True</TypeScriptEmitDecoratorMetadata>
    

  • Save your changes, then right click the project and Reload Project

Your errors should now be gone, and you can continue to build your project.

Reference

https://www.infopulse.com/blog/using-angular-2-in-visual-studio-2015-tutorial/ – The blog post that helped me!

Getting Started with TypeScript


What is TypeScript?

TypeScript works on any browser, any host, any operating system. TypeScript isn’t really a new language. It is an open source project, maintained by Microsoft, configurable to JavaScript version. (ES3, ES6, ES7). It is described as

“TypeScript is a typed superset of JavaScript that compiles to plain JavaScript” – Typescriptlang.org

It adds typing (e.g., String, Boolean, Integers) which for a developer is great because:

  • Allows tooling to autocomplete using intellisense
  • Mistakes in code can be spotted instantly
  • No worries of accidently converting a number into a string, as you might with JavaScript.
  • Supports Standard JavaScript code as well as TypeScript, so you can work with both together.
  • Allow encapsulation through classes and modules
  • Supports contructors, properties and functions
  • Defines Interfaces
  • Saves developer time, and cuts down debugging code.

Installing a compiler

The compiler for TypeScript is called TSC, it works across platforms. It converts TypeScript to JavaScript as browsers do not understand TypeScript. A way to install tsc is as a node.js package with node npm command line.

First you need to install nodejs.

  • Using your browser, navigate to https://nodejs.org and download the current version of NodeJs. (I downloaded the version recommended for most users)
  • Once you have downloaded NodeJs, you can run the installer and work your way through the wizard.
  • Once installed, you can open up a command prompt. Node.js command prompt is also available.

Installing TypeScript Complier

Now you have Node.js installed you can install TypeScript through the node package manager (npm). From the Node.js command prompt, type

npm install -g typescript

Note: The -g flag means to install globally not locally to a folder so that typescript complier works everywhere.

To test that the complier has been installed and working properly, you can perform this quick test.

  • With the command prompt still open, go to a folder of your choice and then type:
    Copy con test.ts
    class myfirstTSClass{
    }
    
  • Press Ctrl + Z and the file is then saved. If you open the file called test.ts in notepad, you will see that a file has been created with the class inside.
  • To compile into JavaScript, type
    tsc test.ts
    
  • In your folder, you should now see a test.js. Open this file in notepad and you should see the following JavaScript.
    var myfirstTSClass = (function () {
        function myfirstTSClass() {
        }
    
        return myfirstTSClass;
    }());
    

Editor Choices

To work with TypeScript you have many different editors you can use for example:

I’m not going to go through how to set up all the different editors, but I will show how to set up Visual Studio and Visual Studio Code as these are the two environments that I typically find myself in when coding. If you head to the TypeScript website (https://typescriptlang.org and click Donwload, you can find information for the other editors there.

Setting Up Visual Studio for TypeScript

Visual Studio is actually really easy, as it is already built into Visual Studio 2015, however it is worth while heading to the TypeScript site and clicking Visual Studio 2015 link (as shown above) to ensure you have the latest version installed within Visual Studio. If you have Visual Studio 2013, you just need to head to the TypeScript site and click the Visual Studio 2013 link.

Install NodeJS for Visual Studio.

Although it’s not a requirement, I recommend installing NodeJS for Visual Studio here too. This will allow you to create NodeJS project within Visual Studio. When I was learning TypeScript, I didn’t always need to write JavaScript that ran in a browser, my hello world application just needed to run within a console window.

In your browser head to VisualStudio.com, on the menu bar, select Features > Application Development > Node.js. Then click the link to “Get Node.js Tools for Visual Studio”

Once downloaded, I then had new project templates available to me in Visual Studio.

Creating a TypeScript Hello World in Visual Studio 2015

  • Open up Visual Studio and create a new Project, select HTML Application with TypeScript, found under the TypeScript template. Click OK.
  • In Solution Explorer you should see a structure like mine. Before we do anything, click the Show All Files button.
  • By opening the app.ts file we can see an example TypeScript class written called Greeter, it displays the current time on the screen.
  • As soon as you hit the Save button, the TypeScript complier automatically runs and creates the corresponding JavaScript and map file. If you refresh the files showing in Solution Explorer, you can see the app.js and app.js.map file. (The JavaScript files are not automatically added to the project, which is why I said click “Show All Files” button).
  • If you open the app.js file, you can see the converted JavaScript.
  • Run the application and in the browser it will tell you the current date and time.

Visual Studio 2013

If you are using Visual Studio 2013, you can install Web Essentials (https://vswebessentials.com) which gives you a JavaScript preview window, to allow side by side TypeScript/JavaScript files.

Setting up Visual Studio Code for TypeScript

As long as you have gone through the steps of installing nodejs and the typescript complier, Visual Studio Code will be able to build TypeScript projects. Unlike Visual Studio 2015, Visual Studio Code requires a bit of configuration for a brand new project to ensure the TypeScript gets converted into JavaScript.

Creating a Hello World in Visual Studio Code

  • Using the command line create a new directory somewhere, and then type code [nameofdirectory] to load it up in VS Code.

    Alternatively using Windows Explorer, you can create the folder, and then right click the folder and select Open with code.

  • Once VS Code has opened, we will create a couple of folders. One called ts and one called js. You do this by clicking on the folder icon in the explorer view.
  • In the ts folder, create a file (pressing the New File button next to the New Folder Button in the explorer view) and call this file helloworld.ts
  • Write the following TypeScript within this file.
class HelloWorld{
      constructor(){
        let divLabel = document.getElementById("mylabel");
        divLabel.innerHTML += "Hello from Visual Studio Code";
    }
}

var helloworld = new HelloWorld();
  • Then outside any folder, create a new file called index.html and put the following HTML within the file.
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <div>
            <h1>Hello World App</h1>
            <div id="mylabel"></div>
        </div>

       <script src="js/app.js"></script>
    </body>
</html>
  • Now if we try to build the project, either calling up the command box (Ctrl + Shift + P), typing Build
    and then select Tasks:Run Build Task or just using the shortcut to the run build tasks (Ctrl + Shift + B) you will see the following message appear at the top of your VS CODE.

  • Click Configure Task Runner and select TypeScript – Watch Mode. This will create a new folder called .vscode and a pre-completed file called tasks.json

  • The tasks.json file contains a json object that configures the TypeScript complier to run. We are going to change the args so that it compiles our TS folder. Change the line from:
    //From
    "args": ["-w", "-p", "."],
    
    //To
    "args":["-w", "-p", "ts/"],
    

    This will ensure that the TSC watches (-w) the project directory (-p) TS/

  • We are now going to create one more file called tsconfig.json
    and this is also going to be created in the TS folder. The presence of this file specifies the root files and the compiler options required to compile the project. https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. In this folder put the following json information.
    {
        "compilerOptions": {
              "sourceMap": true,
                 "target": "es5",
                "outFile": "../js/app.js"
        }
    }
    

    The above ensures a sourcemap file is created so that debugging is available directly within TypeScript files instead of JavaScript files. It is also targeting the EcmaScript5 version of JavaScript, and that all files are compiled into one JavaScript file called app.js located in the JS folder.

  • Now if you run the build task (Ctrl + Shift + B) the project will compile and create two files within the js folder. (app.js and app.js.map).
  • Also note that when you make any changes to the helloworld.ts or any new ts files you might create within the ts directory, and save the file, because we created a watch build task, the app.js file is updated automatically.

Before we run this simple HelloWorldTS app, let me show you an extension that you should download and install in Visual Studio Code.

Installing “View In Browser” Extension

You only will need to do this once, not for each project you create.

  • Click the Extensions button and then type ‘view in browser’ in the search box. Once you have found the extension, click Install
  • Once installed you will need to Enable it. This will request for VS Code to be restarted. Click OK, to continue.

Running HelloWorldTS

With the View In Browser installed, any HTML page you go to in your project and press (Ctrl + F1), will open the page directly in the browser.

Debugging TS files

In this section I’m not going to go into explaining how the Visual Studio Code debugger works, however, I will show you that you can debug using the browser. As stated earlier, you can debug the actual TypeScript files because of the .map file. If you run your project within a browser like before then press F12 to open up the browsers developer tools. I’m using Microsoft Edge, if you are not able to see the .ts file, then press the Load Source map button. (Highlighted)

After you have set a break point, refresh the page, and you can see that you can step through the TS file by pressing F11.

Summary

In this blog post I have explained what TypeScript is, how you can set up TypeScript on your machine using Visual Studio 2013/2015 or Visual Studio Code. We have created 2 simple TypeScript applications, and briefly looked at debugging. This post hasn’t explained how you write TypeScript.