0

As we know, Angular 4+ applications are built with TypeScript.

When we type ng serve in the command line for one these apps, the application runs in the browser and responds to our changes without any .js files apparently being created in our project.

Let's say I have a file, myscript.ts, that exists outside of an Angular application. How can I create a watch scenario for this so that the file runs in Node, but I don't have to create a new file?

Clearly, the case is not that the file has to be compiled into a JavaScript file. We can see when we run ng serve that no new files are created.

4
  • you cant, you have to compile it Commented Apr 17, 2018 at 12:06
  • you can compiler you file to js and than add reference of it in project Commented Apr 17, 2018 at 12:07
  • You have yourself said "apparently" without any .js files created in the project. Well it always does! Commented Apr 17, 2018 at 12:14
  • 1
    I am not really sure whether I understand you as you are mixing angular and webpack running in the background during ng server, and then node running typescript on every change, but I guess you are intersted in ts-node and/or running typescript with tsc -w switch to watch the file changes. Commented Apr 17, 2018 at 12:16

1 Answer 1

3

without any .js files apparently being created in our project.

Sometimes the JS only has to exist in memory, so no actual .js file is necessarily created on your file system, but the compiler is doing the work to convert .ts file to JS at some point, and that is what's served to the browser. The browser only runs JavaScript. However, to make it even more opaque the browser can handle source maps that will map the running JavaScript back to any original source files (in this case .ts files), so in your dev console it really looks like the browser is running TypeScript, but in fact it is running JavaScript that is mapped to original TypeScript source files.

How can I create a watch scenario for this so that the file runs in Node, but I don't have to create a new file?

You could use ts-node. From the docs:

TypeScript Node works by registering the TypeScript compiler for .tsx? and .jsx? extension (when allowJs == true). When node.js has an extension registered (via require.extensions), it will use the extension internally for module resolution. When an extension is unknown to node.js, it handles the file as .js (JavaScript).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.