Visual Studio 2022 - JavaScript - User Guide
Visual Studio 2022 - JavaScript - User Guide
Get started
e OVERVIEW
c HOW-TO GUIDE
b GET STARTED
f QUICKSTART
g TUTORIAL
c HOW-TO GUIDE
Linting JavaScript
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
Visual Studio 2022 provides rich support for JavaScript development, both using
JavaScript directly, and also using the TypeScript programming language , which was
developed to provide a more productive and enjoyable JavaScript development
experience, especially when developing projects at scale. You can write JavaScript or
TypeScript code in Visual Studio for many application types and services.
The option to restore to the legacy JavaScript language service is no longer available.
Users have the new JavaScript language service out-of-the-box. The new language
service is solely based on the TypeScript language service, which is powered by static
analysis. This service enables us to provide you with better tooling, so your JavaScript
code can benefit from richer IntelliSense based on type definitions. The new service is
lightweight and consumes less memory than the legacy service, providing you with
better performance as your code scales. We also improved performance of the language
service to handle larger projects.
TypeScript support
By default, Visual Studio 2022 provides language support for JavaScript and TypeScript
files to power IntelliSense without any specific project configuration.
For compiling TypeScript, Visual Studio gives you the flexibility to choose which version
of TypeScript to use on a per-project basis.
Projects configured for npm, such as Node.js projects, can specify their own version of
the TypeScript language service by adding the TypeScript npm package . You can
specify the version using the npm manager in supported projects. Note: The minimum
supported version of this package is 2.1.
The TypeScript SDK has been deprecated in Visual Studio 2022. Existing projects that
rely on the SDK should be upgraded to use the NuGet package. For projects that cannot
be upgraded immediately, the SDK is still available on the Visual Studio Marketplace
and as an optional component in the Visual Studio installer.
Tip
For projects developed in Visual Studio 2022, we encourage you to use the
TypeScript NuGet or the TypeScript npm package for greater portability across
different platforms and environments. For more information, see Compile
TypeScript code using NuGet and Compile TypeScript code using tsc.
Project templates
Starting in Visual Studio 2022, there is a new JavaScript/TypeScript project type (.esproj)
that allows you to create standalone Angular, React, and Vue projects in Visual Studio.
These front-end projects are created using the framework CLI tools you have installed
on your local machine, so the version of the template is up to you. To migrate from
existing Node.js projects to the new project system, see Migrate Node.js projects.
Within these new projects, you can run JavaScript and TypeScript unit tests, easily add
and connect ASP.NET Core API projects and download your npm modules using the
npm manager. Check out some of the quickstarts and tutorials to get started. For more
information, see Visual Studio tutorials | JavaScript and TypeScript.
7 Note
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
If you haven't already installed Visual Studio, go to the Visual Studio downloads page
to install it for free.
Start window
The first thing you'll see after you launch Visual Studio is the start window. The start
window is designed to help you "get to code" faster. It has options to close or check out
code, open an existing project or solution, create a new project, or simply open a folder
that contains some code files.
If this is the first time you're using Visual Studio, your recent projects list will be empty.
If you work with non-MSBuild based codebases, you'll use the Open a local folder
option to open your code in Visual Studio. For more information, see Develop code in
Visual Studio without projects or solutions. Otherwise, you can create a new project or
clone a project from a source provider such as GitHub or Azure DevOps.
The Continue without code option simply opens the Visual Studio development
environment without any specific project or code loaded. You might choose this option
to join a Live Share session or attach to a process for debugging. You can also press Esc
to close the start window and open the IDE.
Create a project
To continue exploring Visual Studio's features, let's create a new project.
1. On the start window, select Create a new project, and then in the search box type
in javascript to filter the list of project types to those that contain "javascript" in
their name or language type.
Visual Studio provides various kinds of project templates that help you get started
coding quickly. (Alternatively, if you're a TypeScript developer, feel free to create a
project in that language. The UI we'll be looking at is similar for all programming
languages.)
2. Choose a Blank Node.js Web Application project template and click Next.
3. In the Configure your new project dialog box that appears, accept the default
project name and choose Create.
The project is created and a file named server.js opens in the Editor window. The
Editor shows the contents of files, and is where you'll do most of your coding work
in Visual Studio.
Solution Explorer
Solution Explorer, which is typically on the right-hand side of Visual Studio, shows you a
graphical representation of the hierarchy of files and folders in your project, solution, or
code folder. You can browse the hierarchy and navigate to a file in Solution Explorer.
Menus
The menu bar along the top of Visual Studio groups commands into categories. For
example, the Project menu contains commands related to the project you're working in.
On the Tools menu, you can customize how Visual Studio behaves by selecting Options,
or add features to your installation by selecting Get Tools and Features.
Let's open the Error List window by choosing the View menu, and then Error List.
Error List
The Error List shows you errors, warning, and messages regarding the current state of
your code. If there are any errors (such as a missing brace or semicolon) in your file, or
anywhere in your project, they're listed here.
Output window
The Output window shows you output messages from building your project and from
your source control provider.
Let's build the project to see some build output. From the Build menu, choose Build
Solution. The Output window automatically obtains focus and display a successful build
message.
Search box
The search box is a quick and easy way to do pretty much anything in Visual Studio. You
can enter some text related to what you want to do, and it'll show you a list of options
that pertain to the text. For example, imagine you want to increase the build output's
verbosity to display additional details about what exactly build is doing. Here's how you
might do that:
1. Type verbosity into the search box. From the displayed results, choose Projects
and Solutions --> Build and Run under the Options category.
The Options dialog box opens to the Build and Run options page.
2. Under MSBuild project build output verbosity, choose Normal, and then click OK.
This time the Output window shows more verbose logging from the build process,
including which files were copied where.
Send Feedback menu
Should you encounter any problems while you're using Visual Studio, or if you have
suggestions for how to improve the product, you can use the Send Feedback menu at
the top of the Visual Studio window.
Next steps
We've looked at just a few of the features of Visual Studio to get acquainted with the
user interface. To explore further:
See also
Overview of the Visual Studio IDE
More features of Visual Studio 2017
Change theme and font colors
Create a React app
Article • 05/26/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
Prerequisites
Make sure to install the following:
Visual Studio 2022 or later. Go to the Visual Studio downloads page to install it
for free.
npm (https://www.npmjs.com/ ), which is included with Node.js
npx (https://www.npmjs.com/package/npx )
2. Search for React in the search bar at the top and then select Standalone JavaScript
React Project or Standalone TypeScript React Project, based on your preference.
3. Give your project and solution a name.
If you previously selected Standalone JavaScript React Template, when you get to
the Additional information window be sure NOT to check the Add integration for
Empty ASP.NET Web API Project option. This option adds files to your React
template so that it can be hooked up with the ASP.NET Core project, if an ASP.NET
Core project is added.
4. Choose Create, and then wait for Visual Studio to create the project.
Please note that creation of the React project takes a moment because the create-
react-app command that runs at this time also runs the npm install command.
View the project properties
The default project settings allow you to build and debug the project. But, if you need to
change settings, right-click the project in Solution Explorer, select Properties, and then
go the Build or Debugging section.
7 Note
launch.json stores the startup settings associated with the Start button in the
Debug toolbar. Currently, launch.json must be located under the .vscode folder.
7 Note
Check console output for messages, such as a message instructing you to update
your version of Node.js.
Next steps
For ASP.NET Core integration:
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
Prerequisites
Make sure to install the following:
Visual Studio 2022 Preview 2 or later. Go to the Visual Studio downloads page to
install it for free.
npm (https://www.npmjs.com/ ), which is included with Node.js
Angular CLI (https://angular.io/cli ) This can be the version of your choice
2. Search for Angular in the search bar at the top and then select Standalone
TypeScript Angular Project.
3. Give your project and solution a name.
When you get to the Additional information window, be sure NOT to check the
Add integration for Empty ASP.NET Web API Project option. This option adds files
to your Angular template so that it can be hooked up with the ASP.NET Core
project, if an ASP.NET Core project is added.
4. Choose Create, and then wait for Visual Studio to create the project.
7 Note
launch.json stores the startup settings associated with the Start button in the
Debug toolbar. Currently, launch.json must be located under the .vscode folder.
Note, the initial build may take a while, as the Angular CLI will run the npm install
command.
7 Note
Next steps
For ASP.NET Core integration:
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
Prerequisites
Make sure to install the following:
Visual Studio 2022 Preview 2 or later. Go to the Visual Studio downloads page to
install it for free.
npm (https://www.npmjs.com/ ), which is included with Node.js
Vue.js (Installation | Vue.js (vuejs.org) )
Vue.js CLI ((Installation | Vue.js (vuejs.org) )
2. Search for Vue in the search bar at the top and then select Standalone JavaScript
Vue Project or Standalone TypeScript Vue Project, based on your preference.
3. Give your project and solution a name, and then choose Next.
4. Choose Create, and then wait for Visual Studio to create the project.
7 Note
launch.json stores the startup settings associated with the Start button in the
Debug toolbar. Currently, launch.json must be located under the .vscode folder.
7 Note
Next steps
For ASP.NET Core integration:
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
) Important
Starting in Visual Studio 2022, you can alternatively create a Vue project using the
recommended CLI-based project type . The information in this article applies only
to the Node.js project type (.njsproj).
Prerequisites
You must have Visual Studio installed and the Node.js development workload.
If you haven't already installed Visual Studio 2019, go to the Visual Studio
downloads page to install it for free.
If you need to install the workload but already have Visual Studio, go to Tools >
Get Tools and Features..., which opens the Visual Studio Installer. Choose the
Node.js development workload, then choose Modify.
If you don't have it installed, we recommend you install the LTS version from the
Node.js website for best compatibility with outside frameworks and libraries.
Node.js is built for 32-bit and 64-bit architectures. The Node.js tools in Visual
Studio, included in the Node.js workload, support both versions. Only one is
required and the Node.js installer only supports one being installed at a time.
In general, Visual Studio automatically detects the installed Node.js runtime. If it
does not detect an installed runtime, you can configure your project to reference
the installed runtime in the properties page (after you create a project, right-click
the project node, choose Properties, and set the Node.exe path). You can use a
global installation of Node.js or you can specify the path to a local interpreter in
each of your Node.js projects.
Create a project
First, you'll create a Vue.js web application project.
1. If you don't have the Node.js runtime already installed, install the LTS version from
the Node.js website.
Press Esc to close the start window. Type Ctrl + Q to open the search box, type
Basic Vue.js, then choose Basic Vue.js Web application (either JavaScript or
TypeScript). In the dialog box that appears, type the name basic-vuejs, and then
choose Create.
If you don't see the Basic Vue.js Web application project template, you must add
the Node.js development workload. For detailed instructions, see the
Prerequisites.
Visual Studio creates the new project. The new project opens in Solution Explorer
(right pane).
4. Check the Output window (lower pane) for progress on installing the npm
packages required for the application.
5. In Solution Explorer, open the npm node and make sure that all the listed npm
packages are installed.
If any packages are missing (exclamation point icon), you can right-click the npm
node and choose Install Missing npm Packages.
Highlighted in bold is your project, using the name you gave in the New
Project dialog box. On disk, this project is represented by a .njsproj file in
your project folder.
At the top level is a solution, which by default has the same name as your
project. A solution, represented by a .sln file on disk, is a container for one or
more related projects.
The npm node shows any installed npm packages. You can right-click the
npm node to search for and install npm packages using a dialog box.
2. If you want to install npm packages or run Node.js commands from a command
prompt, right-click the project node and choose Open Command Prompt Here.
Add a .vue file to the project
1. In Solution Explorer, right-click any folder such as the src/components folder, and
then choose Add > New Item.
If you don't see all the item templates, choose Show All Templates, and then
choose the item template.
2. Select either JavaScript Vue Single File Component or TypeScript Vue Single File
Component, and then click Add.
2. Check the Output window to see build results, and choose Build from the Show
output from list.
The JavaScript Vue.js project template (and older versions of the TypeScript template)
use the build npm script by configuring a post build event. If you want to modify this
setting, open the project file (<projectname>.njsproj) from Windows Explorer and locate
this line of code:
XML
Congratulations on completing this Quickstart! We hope you learned a little bit about
using the Visual Studio IDE with Vue.js. If you'd like to delve deeper into its capabilities,
continue with a tutorial in the Tutorials section of the table of contents.
Next steps
Create a Vue.js app
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this article, you will learn how to use Visual Studio to build a simple Node.js web app
that uses the Express framework.
Before you begin, here's a quick FAQ to introduce you to some key concepts:
What is Node.js?
What is npm?
A package manager makes it easier to use and share Node.js source code libraries.
The default package manager for Node.js is npm. The npm package manager
simplifies the installation, updating, and uninstallation of libraries.
What is Express?
Express is a server web application framework that Node.js uses to build web apps.
With Express, there are many different ways to create a user interface. The
implementation provided in this tutorial uses the Express application generator's
default template engine, called Pug, to render the front-end.
Prerequisites
Make sure to install the following:
Visual Studio 2022 version 17.4 or later with the ASP.NET and web development
workload installed. Go to the Visual Studio downloads page to install it for free.
If you need to install the workload and already have Visual Studio, go to Tools >
Get Tools and Features..., which opens the Visual Studio Installer. Choose the
ASP.NET and web development workload, then choose Modify.
npm (https://www.npmjs.com/ ), which is included with Node.js
npx (https://www.npmjs.com/package/npx )
Create your app
1. In the Start window (choose File > Start Window to open), select Create a new
project.
2. Search for Express in the search bar at the top and then select JavaScript Express
Application.
7 Note
launch.json stores the startup settings associated with the Start button in the
Debug toolbar. Currently, launch.json must be located under the .vscode folder.
7 Note
Check console output for messages, such as a message instructing you to update
your version of Node.js.
First, if your app is still running, press Shift + F5 or select the red stop button at the top
of the window in order to stop the current session. You might notice that stopping the
session closes the browser showing your app, but leaves behind the command prompt
window running the Node process. For now, go ahead and close any lingering
command prompts. Later in this article, we describe why you might want to leave the
Node process running.
localhost (Edge)
localhost (Chrome)
Debug Dev Env
Launch Node and Browser
Go ahead and select the Launch Node and Browser option. Now, before pressing F5 or
selecting the Start button again, set a breakpoint in index.js (in the routes folder) by
selecting the left gutter before the following line of code: res.render('index', { title:
'Express' });
Tip
You can also put your cursor on a line of code and hit F9 to toggle the breakpoint
for that line.
Then, press F5 or select Debug > Start Debugging to debug your app.
You should see the debugger pause at the breakpoint you just set. While it is paused,
you can inspect your app state. Hovering over variables will let you examine their
properties.
When you're finished inspecting the state, hit F5 to continue, and your app should load
as expected.
This time, if you hit stop, you will notice that both the browser and the command
prompt windows close. To see why, take a closer look at the launch.json.
If you have worked with Visual Studio Code before, the launch.json file will look familiar.
The launch.json here works in much the same way as it does in Visual Studio Code to
denote launch configurations used for debugging. Each entry specifies one or more
targets to be debugged.
The first two entries are browser entries, and they should look something like this:
JSON
{
"name": "localhost (Edge)",
"type": "edge",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}\\public"
},
{
"name": "localhost (Chrome)",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}\\public"
}
You can see in the above entries that the type is set to a browser type. If you launch
with only a browser type as the sole debug target, Visual Studio will debug only the
frontend browser process, and the Node process will be started without a debugger
attached, meaning that any breakpoints that are set in the Node process will not bind.
Upon stopping the session, the Node process will also continue to run. It is intentionally
left running when a browser is the debug target, because if work is solely being done on
the frontend, having the backend process continuously running eases the development
workflow.
At the start of this section, you closed the lingering command prompt window in order
to set breakpoints in the Node process. For the Node process to be debuggable, it must
be restarted with the debugger attached. If a non-debuggable Node process is left
running, attempting to launch the Node process in debug mode (without reconfiguring
the port) will fail.
7 Note
Currently, edge and chrome are the only supported browser types for debugging.
The third entry in the launch.json specifies node as the debug type, and it should look
something like this:
{
"name": "Debug Dev Env",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}/bin",
"program": "${workspaceFolder}/bin/www",
"stopOnEntry": true
}
This entry will launch only the Node process in debug mode. No browser will be
launched.
The fourth entry provided in the "launch.json* is the following compound launch
configuration.
{
"name": "Launch Node and Browser",
"configurations": [
"Debug Dev Env",
"localhost (Edge)"
]
}
There are many other attributes you can use in a launch configuration. For example, you
can hide a configuration from the dropdown, but still have it be referenceable, by
setting the hidden attribute in the presentation object to true .
{
"name": "localhost (Chrome)",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}\\public",
"presentation": {
"hidden": true
}
}
Click Options for a list of attributes you can use to enhance your debugging
experience. Please note that at the moment, only launch configurations are supported.
Any attempt to use an attach configuration will result in a deployment failure.
Tutorial: Create a Node.js and React app
in Visual Studio
Article • 03/24/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
With Visual Studio, you can easily create a Node.js project and use IntelliSense and other
built-in features that support Node.js. In this tutorial, you create a Node.js web app
project from a Visual Studio template. Then, you create a simple app using React.
) Important
Starting in Visual Studio 2022, you can alternatively create a React project using
the new CLI-based project type . Some of the information in this article applies
only to the Node.js project type (.njsproj).
Before you begin, here's a quick FAQ to introduce you to some key concepts:
What is Node.js?
What is npm?
The default package manager for Node.js is npm. A package manager makes it
easier to publish and share Node.js source code libraries. The npm package
manager simplifies library installation, updating, and uninstallation.
What is React?
What is JSX?
JSX is a JavaScript syntax extension typically used with React to describe UI
elements. You must transpile JSX code to plain JavaScript before it can run in a
browser.
What is webpack?
Webpack bundles JavaScript files so they can run in a browser, and can also
transform or package other resources and assets. Webpack can specify a compiler,
such as Babel or TypeScript, to transpile JSX or TypeScript code to plain JavaScript.
Prerequisites
This tutorial requires the following prerequisites:
1. Go to the Visual Studio downloads page to install Visual Studio for free.
2. In the Visual Studio Installer, select the Node.js development workload, and
select Install.
If you have Visual Studio installed but need the Node.js workload:
2. In the Visual Studio Installer, choose the Node.js development workload, and
select Modify to download and install the workload.
If you don't have the Node.js runtime installed, install the LTS version from the
Node.js website . The LTS version has the best compatibility with other
frameworks and libraries.
The Node.js tools in the Visual Studio Node.js workload support both Node.js 32-
bit and 64-bit architecture versions. Visual Studio requires only one version, and
the Node.js installer only supports one version at a time.
Visual Studio usually detects the installed Node.js runtime automatically. If not, you
can configure your project to reference the installed runtime:
1. After you create a project, right-click the project node and select Properties.
2. In the Properties pane, set the Node.exe path to reference a global or local
installation of Node.js. You can specify the path to a local interpreter in each
of your Node.js projects.
Create a project
First, create a Node.js web app project.
1. Open Visual Studio, and press Esc to close the start window.
2. Press Ctrl+Q, type node.js in the search box, and then choose Blank Node.js Web
Application - JavaScript from the dropdown list.
Although this tutorial uses the TypeScript compiler, the steps require that you start
with the JavaScript template.
If you don't see the Blank Node.js Web Application choice, you need to install the
Node.js development workload. For instructions, see the Prerequisites.
Visual Studio creates the new solution and project, and opens the project in the
right pane. The server.js project file opens in the editor in the left pane.
Your project (2), using the name you gave in the Configure your new project
dialog box, is highlighted in bold. In the file system, the project is a .njsproj
file in your project folder.
To see and set project properties and environment variables, press Alt+Enter,
or right-click the project and select Properties from the context menu. You
can work with other development tools, because the project file doesn't make
custom changes to the Node.js project source.
Right-click the npm node to search for and install npm packages. You can
install and update packages by using the settings in package.json and the
right-click options in the npm node.
Npm uses the package.json file (4) to manage dependencies and versions for
locally installed packages. For more information, see Manage npm packages.
Project files (5) appear under the project node. The project startup file,
server.js, shows in bold.
You can set the startup file by right-clicking a file in the project and selecting
Set as Node.js startup file.
react
react-dom
express
path
ts-loader
typescript
webpack
webpack-cli
To install a package:
1. In Solution Explorer, right-click the npm node and select Install New npm
Packages.
2. In the Install New npm Packages dialog box, search for the react package, and
select Install Package to install it.
In the Install New npm Packages dialog box, you can choose to install the most
current package version or to specify a version. If you choose to install the current
versions, but run into unexpected errors later, try installing the exact package
versions listed in the next step.
The Output window in the Visual Studio lower pane shows package installation
progress. Open the Output window by selecting View > Output or pressing
Ctrl+Alt+O. In the Show output from field of the Output window, select Npm.
When installed, the react package appears under the npm node in Solution
Explorer.
The project's package.json file updates with the new package information,
including the package version.
Instead of using the UI to search for and add the rest of the packages one at a time, you
can paste the required package code into package.json.
1. From Solution Explorer, open package.json in the Visual Studio editor. Add the
following dependencies section before the end of the file:
JSON
"dependencies": {
"express": "^4.18.2",
"path": "^0.12.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"ts-loader": "^9.4.2",
"typescript": "^5.0.2",
"webpack": "^5.76.3",
"webpack-cli": "^5.0.1"
},
If the file already has a dependencies section, replace it with the preceding JSON
code. For more information on using the package.json file, see package.json
configuration.
2. Press Ctrl+S or select File > Save package.json to save the changes.
3. In Solution Explorer, right-click the npm node in your project and select Install
npm Packages.
This command runs the npm install command directly to install all the packages
listed in packages.json.
Select the Output window in the lower pane to see installation progress.
Installation might take a few minutes, and you might not see results immediately.
Make sure that you select Npm in the Show output from field in the Output
window.
After installation, the npm modules appear in the npm node in Solution Explorer.
7 Note
You can also install npm packages by using the command line. In Solution
Explorer, right-click the project name and select Open Command Prompt
Here. Use standard Node.js commands to install packages.
app.tsx
webpack-config.js
index.html
tsconfig.json
For this simple app, you add the new project files in the project root. For most apps, you
add the files to subfolders and adjust relative path references accordingly.
1. In Solution Explorer, select the project name and press Ctrl+Shift+A, or right-click
the project name and select Add > New Item.
If you don't see all the item templates, choose Show All Templates, and then
choose the item template.
2. In the Add New Item dialog box, choose TypeScript JSX File, type the name
app.tsx, and select Add or OK.
JavaScript
'use strict';
var path = require('path');
var express = require('express');
The preceding code uses Express to start Node.js as your web application server.
The code sets the port to the port number configured in the project properties,
which by default is 1337. If you need to open the project properties, right-click the
project name in Solution Explorer and select Properties.
JavaScript
declare var require: any
The preceding code uses JSX syntax and React to display a message.
3. Open index.html and replace the body section with the following code:
HTML
<body>
<div id="root"></div>
<!-- scripts -->
<script src="./dist/app-bundle.js"></script>
</body>
This HTML page loads app-bundle.js, which contains the JSX and React code
transpiled to plain JavaScript. Currently, app-bundle.js is an empty file. In the next
section, you configure options to transpile the code.
JSON
module.exports = {
devtool: 'source-map',
entry: "./app.tsx",
mode: "development",
output: {
filename: "./app-bundle.js"
},
resolve: {
extensions: ['.Webpack.js', '.web.js', '.ts', '.js', '.jsx',
'.tsx']
},
module: {
rules: [
{
test: /\.tsx$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'ts-loader'
}
}
]
}
}
The webpack configuration code instructs webpack to use the TypeScript loader to
transpile the JSX.
2. Open tsconfig.json and replace the contents with the following code, which
specifies the TypeScript compiler options:
JSON
{
"compilerOptions": {
"noImplicitAny": false,
"module": "commonjs",
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"jsx": "react"
},
"exclude": [
"node_modules"
],
"files": [
"app.tsx"
]
}
The code specifies app.tsx as the source file.
3. Press Ctrl+Shift+S or select File > Save All to save all changes.
If you see any errors instead of the preceding output, you must resolve them
before your app will work. If your npm package versions are different than the
versions this tutorial specifies, that can cause errors. To fix the errors, try the
following:
Use the exact versions shown in the earlier step, if you didn't already
Install the most recent versions of the npm packages by right-clicking the
npm node in Solution Explorer and choosing Install npm packages.
If one or more package versions are deprecated and result in an error, you might
need to install a more recent version to fix errors. For information on using
package.json to control npm package versions, see package.json configuration.
3. In Solution Explorer, right-click the project node and select Add > Existing Folder.
Anytime you make changes to app.tsx, you must rerun the webpack command. To
automate this step, you can add a build script to transpile the JSX.
1. Open package.json and add the following section after the dependencies section:
JSON
"scripts": {
"build": "webpack-cli --config webpack-config.js"
}
2. To run the app, press F5, select the green arrow button, or select Debug > Start
Debugging.
A Node.js console window opens that shows the debugger listening port.
Visual Studio starts the app by launching the startup file, server.js.
1. In server.js, click in the gutter to the left of the staticPath declaration to set a
breakpoint:
2. To run the app, press F5 or select Debug > Start Debugging.
The debugger pauses at the breakpoint you set, with the current statement
highlighted. Now, you can inspect your app state by hovering over variables that
are currently in scope, using debugger windows like the Locals and Watch
windows.
3. To continue running the app, press F5, select Continue in the Debug toolbar, or
select Debug > Continue.
If you want to use the Chrome Developer Tools or F12 Tools for Microsoft Edge,
press F12. You can use these tools to examine the DOM and interact with the app
by using the JavaScript Console.
1. Select Browse With from the dropdown list in the Debug toolbar.
2. On the Browse With screen, with your preferred browser highlighted, select Add.
4. Give the browser a new friendly name such as Edge with debugging or Chrome with
debugging, and then select OK.
Alternatively, you can open the Run command by right-clicking the Windows Start
button, and enter:
msedge --remote-debugging-port=9222
or
chrome.exe --remote-debugging-port=9222
The browser starts with debugging enabled. The app isn't running yet, so the browser
page is empty.
For app-bundle.js, set the breakpoint in the render() function. To find the
render() function in the app-bundle.js file, press Ctrl+F or select Edit > Find
and Replace > Quick Find, and enter render in the search field.
For app.tsx, set the breakpoint inside the render() function, on the return
statement.
JavaScript
output: {
filename: "./app-bundle.js",
},
output: {
filename: "./app-bundle.js",
devtoolModuleFilenameTemplate: '[resource-path]' // removes
the webpack:/// prefix
},
2. Select your target browser as the debug target in Visual Studio, and then press
Ctrl+F5, or select Debug > Start Without Debugging, to run the app in the
browser.
Tip
Once you attach to the process the first time, you can quickly reattach to the
same process by selecting Debug > Reattach to Process or pressing
Shift+Alt+P.
4. In the Attach to Process dialog box, get a filtered list of browser instances that you
can attach to.
Make sure the correct debugger for your target browser, JavaScript (Chrome) or
JavaScript (Microsoft Edge - Chromium), appears in the Attach to field. Type
chrome or edge in the filter box to filter the results.
5. Select the browser process with the correct host port, localhost in this example.
The port number 1337 or localhost might also appear in the Title field to help you
select the correct process.
6. Select Attach.
The following example shows an Attach to Process window for the Microsoft Edge
browser.
Tip
If the debugger doesn't attach and you see the message Unable to attach to
the process. An operation is not legal in the current state., use Task Manager
to close all instances of the target browser before starting the browser in
debugging mode. Browser extensions may be running and preventing full
debug mode.
7. Because the code with the breakpoint already executed, refresh your browser page
to hit the breakpoint.
Depending on your environment, browser state, and which steps you followed
earlier, you might hit the breakpoint in app-bundle.js or its mapped location in
app.tsx. Either way, you can step through code and examine variables.
While the debugger is paused, you can examine your app state by hovering over
variables and using debugger windows. To step through code, press F11 or select
Debug > Step Into, or press F10 or select Debug > Step Over. To continue running
the code, press F5 or select Continue. For more information on basic debugging
features, see First look at the debugger.
If you can't break into code in app.tsx, retry using Attach to Process to attach
the debugger as described in the previous steps. Make sure that your
environment is set up correctly:
Make sure your source map file includes a reference to ./app.tsx and not
webpack:///./app.tsx, which prevents the Visual Studio debugger from
locating app.tsx.
Or, try using the debugger; statement in app.tsx, or set breakpoints in the
Chrome Developer Tools or F12 Tools for Microsoft Edge instead.
If you can't break into code in app-bundle.js, remove the source map file,
app-bundle.js.map.
Next steps
Deploy the app to Linux App Service
Tutorial: Create an ASP.NET Core app
with React in Visual Studio
Article • 04/25/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this article, you learn how to build an ASP.NET Core project to act as an API backend
and a React project to act as the UI.
Currently, Visual Studio includes ASP.NET Core Single Page Application (SPA) templates
that support Angular and React. The templates provide a built-in Client App folder in
your ASP.NET Core projects that contains the base files and folders of each framework.
You can use the method described in this article to create ASP.NET Core Single Page
Applications that:
Put the client app in a separate project, outside from the ASP.NET Core project
Create the client project based on the framework CLI installed on your computer
7 Note
Prerequisites
Make sure to install the following:
Visual Studio 2022 version 17.5 or later with the ASP.NET and web development
workload installed. Go to the Visual Studio downloads page to install it for free.
If you need to install the workload and already have Visual Studio, go to Tools >
Get Tools and Features..., which opens the Visual Studio Installer. Choose the
ASP.NET and web development workload, then choose Modify.
npm (https://www.npmjs.com/ ), which is included with Node.js
npx (https://www.npmjs.com/package/npx )
2. Search for React in the search bar at the top and then select React and ASP.NET
Core (Preview). This is a JavaScript template.
3. Give your project and solution a name, and then choose Create to create the
solution.
Once the project is created, Solution Explorer should look like this:
Compared to the standalone React template, you see some new and modified files
for integration with ASP.NET Core:
aspnetcore-https.js
aspnetcore-react.js
setupProxy.js
App.js (modified)
App.test.js (modified)
4. Select an installed browser from the Debug toolbar, such as Chrome or Microsoft
Edge.
If the browser you want is not yet installed, install the browser first, and then select
it.
7 Note
launch.json stores the startup settings associated with the Start button in the
Debug toolbar. Currently, launch.json must be located under the .vscode
folder.
7 Note
You should see a React app appear, that is populated via the API. If you don't see the
app, see Troubleshooting.
Publish the project
Starting in Visual Studio 2022 version 17.3, you can publish the integrated solution using
the Visual Studio Publish tool.
7 Note
To use publish, create your JavaScript project using Visual Studio 2022 version 17.3
or later.
1. In Solution Explorer, right-click the ASP.NET Core project and choose Add >
Project Reference.
3. Right-click the ASP.NET Core project in Solution Explorer and choose Unload
project.
4. In the .csproj file, update the project reference and add <ReferenceOutputAssembly>
with the value set to false .
When you've updated the reference, it should look like this (substituting your own
project folder and project name).
XML
<ProjectReference
Include="..\reactprojectfolder\reactprojectname.esproj">
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
C#
7. To publish, right click the ASP.NET Core project, choose Publish, and select options
to match your desired publish scenario, such as Azure, publish to a folder, et al.
The publish process takes more time than it does for just an ASP.NET Core project,
since the npm run build command gets invoked when publishing.
You can modify the npm run build command using the Production Build
Command in the React project properties. To modify it, right-click the React project
in Solution Explorer and choose Properties.
Troubleshooting
Proxy error
You may see the following error:
If you see this issue, most likely the frontend started before the backend. Once you see
the backend command prompt up and running, just refresh the React App in the
browser.
Verify ports
If the weather data does not load correctly, you may also need to verify that your ports
are correct.
1. Make sure that the port numbers match. Go to the launchSettings.json file in your
ASP.NET Core project (in the Properties folder). Get the port number from the
applicationUrl property.
If there are multiple applicationUrl properties, look for one using an https
endpoint. It should look similar to https://localhost:7049 .
2. Then, go to the setupProxy.js file for your React project (look in the src folder).
Update the target property to match the applicationUrl property in
launchSettings.json. When you update it, that value should look similar to this:
JavaScript
target: 'https://localhost:7049',
Next steps
For more information about SPA applications in ASP.NET Core, see the React section
under Developing Single Page Apps. The linked article provides additional context for
project files such as aspnetcore-https.js, aspnetcore-react.js, and setupProxy.js, although
details of the implementation are different based on the template differences. For
example, instead of a ClientApp folder, the React files are contained in a separate
project.
Tutorial: Create an ASP.NET Core app
with Angular in Visual Studio
Article • 04/25/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this article, you learn how to build an ASP.NET Core project to act as an API backend
and an Angular project to act as the UI.
Currently, Visual Studio includes ASP.NET Core Single Page Application (SPA) templates
that support Angular and React. The templates provide a built-in Client App folder in
your ASP.NET Core projects that contains the base files and folders of each framework.
You can use the method described in this article to create ASP.NET Core Single Page
Applications that:
Put the client app in a separate project, outside from the ASP.NET Core project
Create the client project based on the framework CLI installed on your computer
7 Note
Prerequisites
Make sure to install the following:
Visual Studio 2022 version 17.5 or later with the ASP.NET and web development
workload installed. Go to the Visual Studio downloads page to install it for free.
If you need to install the workload and already have Visual Studio, go to Tools >
Get Tools and Features..., which opens the Visual Studio Installer. Choose the
ASP.NET and web development workload, then choose Modify.
npm (https://www.npmjs.com/ ), which is included with Node.js
Angular CLI (https://angular.io/cli ) This can be the version of your choice
2. Search for Angular in the search bar at the top and then select Angular and
ASP.NET Core (Preview).
Once the project is created, Solution Explorer should look like this:
Compared to the standalone Angular template, you see some new and modified
files for integration with ASP.NET Core:
aspnetcore-https.js
proxy.conf.js
package.json(modified)
angular.json(modified)
app.components.ts
app.module.ts
7 Note
launch.json stores the startup settings associated with the Start button in the
Debug toolbar. Currently, launch.json must be located under the .vscode
folder.
7 Note
Check console output for messages, such as a message instructing you to update
your version of Node.js.
You should see an Angular app appear, that is populated via the API. If you don't see the
app, see Troubleshooting.
Publish the project
Starting in Visual Studio 2022 version 17.3, you can publish the integrated solution using
the Visual Studio Publish tool.
7 Note
To use publish, create your JavaScript project using Visual Studio 2022 version 17.3
or later.
1. In Solution Explorer, right-click the ASP.NET Core project and choose Add >
Project Reference.
3. Right-click the ASP.NET Core project in Solution Explorer and choose Unload
Project.
4. In the .csproj file, update the project reference and add <ReferenceOutputAssembly>
with the value set to false .
When you've updated the reference, it should look like this (substituting your own
project folder and project name).
XML
<ProjectReference
Include="..\angularprojectfolder\angularprojectname.esproj">
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
C#
7. To publish, right click the ASP.NET Core project, choose Publish, and select options
to match your desired publish scenario, such as Azure, publish to a folder, et al.
The publish process takes more time than it does for just an ASP.NET Core project,
since the npm run build command gets invoked when publishing.
You can modify the npm run build command using the Production Build
Command in the Angular project properties. To modify it, right-click the Angular
project in Solution Explorer and choose Properties.
Troubleshooting
Proxy error
You may see the following error:
If you see this issue, most likely the frontend started before the backend. Once you see
the backend command prompt up and running, just refresh the Angular App in the
browser.
Verify port
If the weather data does not load correctly, you may also need to verify that your ports
are correct.
1. Go to the launchSettings.json file in your ASP.NET Core project (in the Properties
folder). Get the port number from the applicationUrl property.
If there are multiple applicationUrl properties, look for one using an https
endpoint. It should look similar to https://localhost:7049 .
2. Then, go to the proxy.conf.js file for your Angular project (look in the src folder).
Update the target property to match the applicationUrl property in
launchSettings.json. When you update it, that value should look similar to this:
JavaScript
target: 'https://localhost:7049',
Next steps
For more information about SPA applications in ASP.NET Core, see the Angular section
under Developing Single Page Apps. The linked article provides additional context for
project files such as aspnetcore-https.js and proxy.conf.js, although details of the
implementation are different due to project template differences. For example, instead
of a ClientApp folder, the Angular files are contained in a separate project.
Tutorial: Create an ASP.NET Core app
with Vue in Visual Studio
Article • 04/25/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this article, you learn how to build an ASP.NET Core project to act as an API backend
and a Vue project to act as the UI.
Currently, Visual Studio includes ASP.NET Core Single Page Application (SPA) templates
that support Angular, React, and Vue. The templates provide a built-in Client App folder
in your ASP.NET Core projects that contains the base files and folders of each
framework.
You can use the method described in this article to create ASP.NET Core Single Page
Applications that:
Put the client app in a separate project, outside from the ASP.NET Core project
Create the client project based on the framework CLI installed on your computer
7 Note
Prerequisites
Make sure to install the following:
Visual Studio 2022 version 17.5 or later with the ASP.NET and web development
workload installed. Go to the Visual Studio downloads page to install it for free.
If you need to install the workload and already have Visual Studio, go to Tools >
Get Tools and Features..., which opens the Visual Studio Installer. Choose the
ASP.NET and web development workload, then choose Modify.
npm (https://www.npmjs.com/ ), which is included with Node.js
Vue CLI (https://cli.vuejs.org/ )
Create the frontend app
1. In the Start window (choose File > Start Window to open), select Create a new
project.
2. Search for Vue in the search bar at the top and then select Vue and ASP.NET Core
(Preview) with either JavaScript or TypeScript as the selected language.
3. Give your project and solution a name and then choose Create.
Once the project is created, Solution Explorer should look like this:
Compared to the standalone Vue template, you see some new and modified files
for integration with ASP.NET Core:
aspnetcore-https.js
vue.config.json (modified)
HelloWorld.vue (modified)
package.json (modified)
7 Note
launch.json stores the startup settings associated with the Start button in the
Debug toolbar. Currently, launch.json must be located under the .vscode
folder.
7 Note
Check console output for messages, such as a message instructing you to update
your version of Node.js.
You should see the Vue app appear, that is populated via the API. If you don't see the
app, see Troubleshooting.
Publish the project
Starting in Visual Studio 2022 version 17.3, you can publish the integrated solution using
the Visual Studio Publish tool.
7 Note
To use publish, create your JavaScript project using Visual Studio 2022 version 17.3
or later.
1. In Solution Explorer, right-click the ASP.NET Core project and choose Add >
Project Reference.
3. Right-click the ASP.NET Core project in Solution Explorer and choose Unload
project.
4. In the .csproj file, update the project reference and add <ReferenceOutputAssembly>
with the value set to false .
When you've updated the reference, it should look like this (substituting your own
project folder and project name).
XML
<ProjectReference Include="..\vueprojectfolder\vueprojectname.esproj">
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
C#
7. To publish, right click the ASP.NET Core project, choose Publish, and select options
to match your desired publish scenario, such as Azure, publish to a folder, et al.
The publish process takes more time than it does for just an ASP.NET Core project,
since the npm run build command gets invoked when publishing.
You can modify the npm run build command using the Production Build
Command in the Vue project properties. To modify it, right-click the Vue project in
Solution Explorer and choose Properties.
Troubleshooting
Proxy error
You may see the following error:
If you see this issue, most likely the frontend started before the backend. Once you see
the backend command prompt up and running, just refresh the Vue app in the browser.
Verify ports
If the weather data does not load correctly, you may also need to verify that your ports
are correct.
1. Make sure that the port numbers match. Go to the launchSettings.json file in your
ASP.NET Core project (in the Properties folder). Get the port number from the
applicationUrl property.
If there are multiple applicationUrl properties, look for one using an https
endpoint. It should look similar to https://localhost:5001 .
2. Then, go to the vue.config.js file for your Vue project. Update the target property to
match the applicationUrl property in launchSettings.json. When you update it,
that value should look similar to this:
JavaScript
target: 'https://localhost:5001',
Docker
If you enable Docker support while creating the web API project, the backend may start
up using the Docker profile and not listen on the configured port 5001. To resolve:
Edit the Docker profile in the launchSettings.json by adding the following properties:
JSON
"httpPort": 5003,
"sslPort": 5001
1. In the Solution properties, set your backend app as the startup project.
2. In the Debug menu, switch the profile using the Start button drop-down menu to
the profile for your backend app.
3. Next, in the Solution properties, reset to multiple startup projects.
Next steps
For more information about SPA applications in ASP.NET Core, see Developing Single
Page Apps. The linked article provides additional context for project files such as
aspnetcore-https.js, although details of the implementation are different due to
differences between the project templates and the Vue.js framework vs. other
frameworks. For example, instead of a ClientApp folder, the Vue files are contained in a
separate project.
Tutorial: Create an ASP.NET Core app
with TypeScript in Visual Studio
Article • 05/23/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this tutorial for Visual Studio development using ASP.NET Core and TypeScript, you
create a simple web application, add some TypeScript code, and then run the app.
Starting in Visual Studio 2022, if you want to use Angular or Vue with ASP.NET Core, it is
recommended that you use the ASP.NET Core Single Page Application (SPA) templates
to create an ASP.NET Core app with TypeScript. For more information, see the Visual
Studio tutorials for Angular or Vue.
Prerequisites
You must have Visual Studio installed and the ASP.NET web development
workload.
If you haven't already installed Visual Studio 2022, go to the Visual Studio
downloads page to install it for free.
If you need to install the workload but already have Visual Studio, go to Tools >
Get Tools and Features..., which opens the Visual Studio Installer. Choose the
ASP.NET and web development workload, then choose Modify.
7 Note
To start with an empty ASP.NET Core project and add a TypeScript frontend, see
ASP.NET Core with TypeScript instead.
In this tutorial, you begin with a simple project containing code for an ASP.NET Core
MVC app.
In Visual Studio 2022, choose Create a new project in the start window. If the start
window is not open, choose File > Start Window. Type web app, choose C# as the
language, then choose ASP.NET Core Web App (Model-View-Controller), and
then choose Next. On the next screen, name the project, and then choose Next.
Choose either the recommended target framework or .NET 6, and then choose
Create.
If you don't see the ASP.NET Core Web App project template, you must add the
ASP.NET and web development workload. For detailed instructions, see the
Prerequisites.
Visual Studio creates the new solution and opens your project in the right pane.
2. Right-click the project node and choose Add > New Item. Choose the TypeScript
JSON Configuration File, and then click Add.
If you don't see all the item templates, choose Show All Templates, and then
choose the item template.
Visual Studio adds the tsconfig.json file to the project root. You can use this file to
configure options for the TypeScript compiler.
3. Open tsconfig.json and replace the default code with the following code:
JSON
{
"compileOnSave": true,
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"outDir": "wwwroot/js"
},
"include": [
"scripts/**/*"
]
}
The outDir option specifies the output folder for the plain JavaScript files that are
transpiled by the TypeScript compiler.
4. In Solution Explorer, right-click the project node and choose Add > New Folder.
Use the name scripts for the new folder.
5. Right-click the scripts folder and choose Add > New Item. Choose the TypeScript
File, type the name app.ts for the filename, and then click Add.
If you don't see all the item templates, choose Show All Templates, and then
choose the item template.
Visual Studio adds app.ts to the scripts folder.
ts
function TSButton() {
let name: string = "Fred";
document.getElementById("ts-example").innerHTML = greeter(user);
}
class Student {
fullName: string;
constructor(public firstName: string, public middleInitial: string,
public lastName: string) {
this.fullName = firstName + " " + middleInitial + " " +
lastName;
}
}
interface Person {
firstName: string;
lastName: string;
}
To test this, remove .lastName from the greeter function, then retype the ".", and
you see IntelliSense.
HTML
<div id="ts-example">
<br />
<button type="button" class="btn btn-primary btn-md"
onclick="TSButton()">
Click Me
</button>
</div>
JavaScript
<script src="~/js/app.js"></script>
Although the app builds automatically when you run it, we want to take a look at
something that happens during the build process.
2. Open the wwwroot/js folder, and you find two new files, app.js and the source map
file, app.js.map. These files are generated by the TypeScript compiler.
In the browser window, you will see the Welcome heading and the Click Me
button.
2. Click the button to display the message we specified in the TypeScript file.
7 Note
The application pauses at the breakpoint. Now, you can inspect variables and use
debugger features.
7 Note
For ASP.NET Core projects, you can also use Library Manager or yarn instead
of npm to install client-side JavaScript and CSS files.
2. In this example, add a TypeScript definition file for jQuery to your project. Include
the following in your package.json file.
JSON
"devDependencies": {
"@types/jquery": "3.5.1"
}
This adds TypeScript support for jQuery. The jQuery library itself is already included
in the MVC project template (look under wwwroot/lib in Solution Explorer). If you
are using a different template, you may need to include the jquery npm package as
well.
3. If the package in Solution Explorer is not installed, right-click the npm node and
choose Restore Packages.
7 Note
In some scenarios, Solution Explorer may indicate that an npm package is out
of sync with package.json due to a known issue described here . For
example, the package may appear as not installed when it is installed. In most
cases, you can update Solution Explorer by deleting package.json, restarting
Visual Studio, and re-adding the package.json file as described earlier in this
article.
4. In Solution Explorer, right-click the scripts folder and choose Add > New Item.
If you don't see all the item templates, choose Show All Templates, and then
choose the item template.
var jqtest = {
showMsg: function (): void {
let v: any = jQuery.fn.jquery.toString();
let content: any = $("#ts-example-2")[0].innerHTML;
alert(content.toString() + " " + v + "!!");
$("#ts-example-2")[0].innerHTML = content + " " + v + "!!";
}
};
jqtest.showMsg();
For simplicity, this code displays a message using jQuery and an alert.
With TypeScript type definitions for jQuery added, you get IntelliSense support on
jQuery objects when you type a "." following a jQuery object, as shown here.
HTML
<script src="~/js/app.js"></script>
<script src="~/js/library.js"></script>
HTML
<div>
<p id="ts-example-2">jQuery version is:</p>
</div>
9. Press F5 (Debug > Start Debugging) to run the application.
Click OK in the alert to see the page updated to jQuery version is: 3.3.1!!.
Next steps
You may want to learn more details about using TypeScript with ASP.NET Core. If you
are interested in Angular programming in Visual Studio, you can use the Angular
language service extension for Visual Studio.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
This tutorial walks you through the task of creating a simple Node.js application and
publishing it to Azure.
When publishing a Node.js application to Azure, there are several options. These include
Azure App Service, a VM running an OS of your choosing, Azure Container Service (AKS)
for management with Kubernetes, a Container Instance using Docker, and more. For
more details on each of these options, see Compute .
For this tutorial, you deploy the app to Linux App Service. Linux App Service deploys a
Linux Docker container to run the Node.js application (as opposed to the Windows App
Service, which runs Node.js apps behind IIS on Windows).
This tutorial shows how to create a Node.js application starting from a template installed
with the Node.js Tools for Visual Studio, push the code to a repository on GitHub, and
then provision an Azure App Service via the Azure web portal so that you can deploy
from the GitHub repository. To use the command-line to provision the Azure App
Service and push the code from a local Git repository, see Create Node.js App.
Prerequisites
You must have Visual Studio installed and the Node.js development workload.
If you haven't already installed Visual Studio 2019, go to the Visual Studio
downloads page to install it for free.
If you need to install the workload but already have Visual Studio, go to Tools >
Get Tools and Features..., which opens the Visual Studio Installer. Choose the
Node.js development workload, then choose Modify.
You must have the Node.js runtime installed.
If you don't have it installed, install the LTS version from the Node.js website. In
general, Visual Studio automatically detects the installed Node.js runtime. If it does
not detect an installed runtime, you can configure your project to reference the
installed runtime in the properties page (after you create a project, right-click the
project node and choose Properties).
Press Esc to close the start window. Type Ctrl + Q to open the search box, type
Node.js, then choose Create new Basic Azure Node.js Express 4 application
(TypeScript). In the dialog box that appears, choose Create.
If you don't see the Basic Azure Node.js Express 4 application project template,
you must add the Node.js development workload. For detailed instructions, see
the Prerequisites.
Visual Studio creates the project and opens it in Solution Explorer (right pane).
3. Press F5 to build and run the app, and make sure that everything is running as
expected.
4. Select File > Add to source control to create a local Git repository for the project.
At this point, a Node.js app using the Express framework and written in TypeScript
is working and checked in to local source control.
2. From the menu select View > Other Windows > GitHub.
3. If you don't see the Get Started button in the GitHub window, click File > Add to
Source Control and wait for the UI to update.
If you are already connected to GitHub, the toolbox appears similar to the
following illustration.
5. Complete the fields for the new repository to publish, and then click Publish.
In the next section, you learn how to publish from this repository to an Azure App
Service on Linux.
2. Select App Services from the list of services on the left, and then click Add.
3. If required, create a new Resource Group and App Service plan to host the new
app.
4. Make sure to set the OS to Linux, and set Runtime Stack to the required Node.js
version, as shown in the illustration.
5. Click Create to create the App Service.
6. After it is deployed, go to the Application settings section, and add a setting with
a name of SCM_SCRIPT_GENERATOR_ARGS and a value of --node .
2 Warning
8. After it is deployed, open the App Service and select Deployment options.
9. Click Choose source, and then choose GitHub, and then configure any required
permissions.
10. Select the repository and branch to publish, and then select OK.
The site is now running the Node.js application from the GitHub repository, and it
is accessible at the URL created for the Azure App Service (by default the name
given to the Azure App Service followed by ".azurewebsites.net").
TypeScript
2. Build the code and test it locally, then check it in and push to GitHub.
In the Azure portal, it takes a few moments to detect changes in the GitHub repo,
and then a new sync of the deployment starts. This looks similar to the following
illustration.
3. Once deployment is complete, navigate to the public site and append /api to the
URL. The JSON response gets returned.
Troubleshooting
If the node.exe process dies (that is, an unhandled exception occurs), the container
restarts.
When the container starts up, it runs through various heuristics to figure out how
to start the Node.js process. Details of the implementation can be seen at
generateStartupCommand.js .
You can connect to the running container via SSH for investigations. This is easily
done using the Azure portal. Select the App Service, and scroll down the list of
tools until reaching SSH under the Development Tools section.
To aid in troubleshooting, go to the Diagnostics logs settings for the App Service,
and change the Docker Container logging setting from Off to File System. Logs
are created in the container under /home/LogFiles/_docker.log*, and can be
accessed on the box using SSH or FTP(S).
A custom domain name may be assigned to the site, rather than the
*.azurewebsites.net URL assigned by default. For more details, see the topic Map
Custom Domain.
Deploying to a staging site for further testing before moving into production is a
best practice. For details on how to configure this, see the topic Create staging
environments.
See the App Service on Linux FAQ for more commonly asked questions.
Next steps
In this tutorial, you learned how create a Linux App Service and deploy a Node.js
application to the service. You may want to learn more about Linux App Service.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
Starting in Visual Studio 2022 version 17.7 Preview 1, you can convert existing projects
based on the older Node.js project system (.njsproj) to the new JavaScript project system
(.esproj). By migrating the project, you can benefit from project system updates such as
npm dependency management, unit testing support, and launch config settings.
Right-click the project node for your Node.js project. You should see one of two options:
Convert to New JavaScript Project Experience or Convert to New TypeScript Project
Experience. Select the available option to migrate your project to the new project
system.
After you choose Convert, a conversion log text file gets created and then it opens. The
log file details the steps that occurred during the migration.
If anything goes wrong during the migration, you can choose the Revert Project to Old
Experience option so that the conversion will be reverted. If you encounter any problem
during this process, please the Report a problem feature in Visual Studio.
Learn to use the code editor for
JavaScript
Article • 06/05/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this short introduction to the code editor in Visual Studio, we'll look at some of the
ways that Visual Studio makes writing, navigating, and understanding code easier.
Tip
If you haven't already installed Visual Studio, go to the Visual Studio downloads
page to install it for free. If you are developing Node.js applications, you need to
install the Node.js development workload with Visual Studio. For more information
in getting the language service for TypeScript, see TypeScript support.
This article assumes you're already familiar with JavaScript development. If you aren't,
we suggest you look at a tutorial such as Create a Node.js and Express app first.
1. With your project open in Visual Studio, right-click on a folder or your project node
in Solution Explorer (right pane), and choose Add > New Item.
If you don't see all the item templates, choose Show All Templates, and then
choose the item template.
2. In the New File dialog box, under the General category, choose the file type that
you want to add, such as JavaScript File, and then choose Open.
The new file gets added to your project and it opens in the editor.
IntelliSense can also show you information about types when you hover over
programming elements.
To provide IntelliSense information, the language service can use TypeScript d.ts files
and JSDoc comments. For most common JavaScript libraries, d.ts files are automatically
acquired. For more details about how IntelliSense information is acquired, see JavaScript
IntelliSense. If you are interested in AngularJS programming in Visual Studio, you can
use the AngularJS language service extension for Visual Studio to get IntelliSense.
Check syntax
The language service uses ESLint to provide syntax checking and linting. If you need to
set options for syntax checking in the editor, select Tools > Options >
JavaScript/TypeScript > Linting. The linting options point you to the global ESLint
configuration file.
In the following code, you see green syntax highlighting (green squiggles) on the
expression. Hover over the syntax highlighting.
The last line of this message tells you that the language service expected a comma ( , ).
The green squiggle indicates a warning. Red squiggles indicate an error.
In the lower pane, you can click the Error List tab to see the warning and description
along with the filename and line number.
You can fix this code by adding the comma ( , ) before "data" .
Select one or more lines of code in the editor and then choose the Comment out the
selected lines button on the toolbar. If you prefer to use the keyboard, press Ctrl+K,
Ctrl+C.
The JavaScript comment characters // are added to the beginning of each selected line
to comment out the code.
Collapse code blocks
If you need to unclutter your view of some regions of code, you can collapse it. Choose
the small gray box with the minus sign inside it in the margin of the first line of a
function. Or, if you're a keyboard user, place the cursor anywhere in the constructor
code and press Ctrl+M, Ctrl+M.
The code block collapses to just the first line, followed by an ellipsis ( ... ). To expand
the code block again, click the same gray box that now has a plus sign in it, or press
Ctrl+M, Ctrl+M again. This feature is called Outlining and is especially useful when
you're collapsing long functions or entire classes.
View definitions
The Visual Studio editor makes it easy to inspect the definition of a type, function, etc.
One way is to navigate to the file that contains the definition, for example by choosing
Go to Definition anywhere the programming element is referenced. An even quicker
way that doesn't move your focus away from the file you're working in is to use Peek
Definition. Let's peek at the definition of the render method in the example below.
Right-click on render and choose Peek Definition from the content menu. Or, press
Alt+F12.
A pop-up window appears with the definition of the render method. You can scroll
within the pop-up window, or even peek at the definition of another type from the
peeked code.
Close the peeked definition window by choosing the small box with an "x" at the top
right of the pop-up window.
Place your cursor where you want to insert the snippet, right-click and choose Snippet >
Insert Snippet.
An Insert Snippet box appears in the editor. Choose General and then double-click the
for item in the list.
This adds the for loop snippet to your code:
JavaScript
You can look at the available code snippets for your language by choosing Edit >
IntelliSense > Insert Snippet, and then choosing your language's folder.
See also
Code snippets
Navigate code
Outlining
Go To Definition and Peek Definition
Refactoring
Use IntelliSense
JavaScript IntelliSense
Article • 02/22/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
Visual Studio provides a powerful JavaScript editing experience right out of the box.
Powered by a TypeScript-based language service, Visual Studio delivers rich IntelliSense,
support for modern JavaScript features, and productivity features such as Go to
Definition, refactoring, and more.
For more information about the general IntelliSense functionality of Visual Studio, see
Using IntelliSense.
For a variable or property, the type is typically the type of the value used to initialize it
or the most recent value assignment.
JavaScript
nextItem = "box";
nextItem; // now we know nextItem is a string
For a function, the return type can be inferred from the return statements.
For function parameters, there is currently no inference, but there are ways to work
around this using JSDoc or TypeScript .d.ts files (see later sections).
JavaScript
function Foo(param1) {
this.prop = param1;
}
Foo.prototype.getIt = function () { return this.prop; };
// Foo will appear as a class, and instances will have a 'prop' property and
a 'getIt' method.
exports.Foo = Foo;
// This file will appear as an external module with a 'Foo' export.
// Note that assigning a value to "module.exports" is also supported.
JavaScript
/**
* @type {{a: boolean, b: boolean, c: number}}
*/
var x = {a: true};
x.b = false;
x. // <- "x" is shown as having properties a, b, and c of the types
specified
As mentioned, function parameters are never inferred. However, using the JSDoc @param
tag you can add types to function parameters as well.
JavaScript
/**
* @param {string} param1 - The first argument to this function
*/
function Foo(param1) {
this.prop = param1; // "param1" (and thus "this.prop") are now of type
"string".
}
See the JsDoc information in Type Checking JavaScript Files for the JsDoc annotations
currently supported.
Below, we show a simple example of a TypeScript definition file providing such type
information (via an interface) to a JavaScript file in the same project (using a JsDoc tag).
By default, the language service tries to detect which JavaScript libraries are in use, and
then automatically download and reference the corresponding .d.ts file that describes
the library in order to provide richer IntelliSense. The files are downloaded to a cache
located under the user folder at %LOCALAPPDATA%\Microsoft\TypeScript.
7 Note
Currently, auto-detection works for dependencies downloaded from npm (by reading
the package.json file), Bower (by reading the bower.json file), and for loose files in your
project that match a list of roughly the top 400 most popular JavaScript libraries. For
example, if you have jquery-1.10.min.js in your project, the file jquery.d.ts will be fetched
and loaded in order to provide a better editing experience. This .d.ts file will have no
impact on your project.
See also
Using IntelliSense
JavaScript support (Visual Studio for Mac)
Linting JavaScript in Visual Studio
Article • 06/29/2023
Linting JavaScript and TypeScript in Visual Studio is powered by ESLint . If you're new
to ESLint, you can begin by checking their documentation .
In the options page, you can also modify the set of files that you want to lint. By default,
all file extensions that can be linted (.js, .jsx, .ts, .tsx, .vue, .html) will be linted. The HTML
LSP-based editor must be enabled for linting Vue and HTML files. The respective setting
can be found in Tools > Options > Environment > Preview Features.
You can override these options in some project types, like the standalone React project
templates. In these projects, you can override the settings from the Tools > Options
page using project properties:
Installing ESLint dependencies
Once linting is enabled, the necessary dependencies need to be installed. Dependencies
include the ESLint npm package and other plugins applicable to your project. This
package can be installed locally in each project where you want to enable linting, or you
can install it globally using npm install -g eslint . However, a global installation isn't
recommended because plugins and shareable configs always need to be installed
locally.
Starting in Visual Studio 2022 version 17.7 Preview 2, you can also use the ESLint Path
setting in Tools > Options > Text Editor > JavaScript/TypeScript > Linting to specify a
directory from which to load ESLint. This is useful when ESLint is installed globally, where
you might set the corresponding path to C:\Program Files\nodejs\node_modules.
Depending on the files you want to lint, other ESLint plugins may be needed. For
example, you may need TypeScript ESLint , which enables ESLint to run on TypeScript
code and includes rules that are specific to the extra type information.
When ESLint is enabled but the ESLint npm package isn't found, a gold bar is displayed
that allows you to install ESLint as a local npm development dependency.
Similarly, when an .eslintrc file isn't found, a gold bar is displayed to run a configuration
wizard that will install the plugins applicable to the current project.
Disabling linting rules and auto-fixes
You can disable linting errors on a specific line or file . You can disable the errors by
using the Quick Actions lightbulb menu:
The following illustration shows the result if you disable a linting error for the selected
line of code.
In addition, auto-fix code actions allow you to apply an auto-fix to address the
respective linting error.
Troubleshooting
You can open the ESLint Language Extension pane in the Output window to see any
error messages or other logs that might explain the problem.
Compile TypeScript code (Node.js)
Article • 05/26/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
You can add TypeScript support to your projects using the TypeScript SDK or by using
npm. The TypeScript SDK is available by default in the Visual Studio installer.
We encourage you to use the TypeScript npm package for greater portability across
different platforms and environments.
For ASP.NET Core projects, it's recommended that you use the NuGet package instead.
1. Follow instructions to install the Node.js development workload and the Node.js
runtime.
For a simple Visual Studio integration, create your project using one of the Node.js
TypeScript templates, such as the Blank Node.js Web Application template. Else,
use either a Node.js JavaScript template included with Visual Studio and follow
instructions here. Or, use an Open Folder project.
2. If your project doesn't already include it, install the TypeScript npm package .
From Solution Explorer (right pane), open the package.json in the project root. The
packages listed correspond to packages under the npm node in Solution Explorer.
For more information, see Manage npm packages.
For a Node.js project, you can install the TypeScript npm package using the
command line or the IDE. To install using the IDE, right-click the npm node in
Solution Explorer, choose Install New npm package, search for TypeScript, and
install the package.
Check the npm option in the Output window to see package installation progress.
The installed package shows up under the npm node in Solution Explorer.
3. If your project doesn't already include it, add a tsconfig.json file to your project
root. To add the file, right-click the project node and choose Add > New Item.
Choose the TypeScript JSON Configuration File, and then click Add.
If you don't see all the item templates, choose Show All Templates, and then
choose the item template.
Visual Studio adds the tsconfig.json file to the project root. You can use this file to
configure options for the TypeScript compiler.
4. Open tsconfig.json and update to set the compiler options that you want.
JSON
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"outDir": "dist"
},
"include": [
"scripts/**/*"
]
}
In this example:
TypeScript
JSON
"scripts": {
"build": "tsc --build",
"clean": "tsc --build --clean"
},
To build using a third-party tool like webpack, you can add a command-line build
script to your package.json file:
JSON
"scripts": {
"build": "webpack-cli app.tsx --config webpack-config.js"
}
For an example of using webpack with React and a webpack configuration file, see
Create a web app with Node.js and React.
3. If you need to configure options such as the startup page, path to the Node.js
runtime, application port, or runtime arguments, right-click the project node in
Solution Explorer, and choose Properties.
7 Note
When configuring third-party tools, Node.js projects don't use the paths that
are configured under Tools > Options > Projects and solutions > Web
Package Management > External Web Tools. These settings are used for
other project types.
The app builds automatically when you run it. However, the following might occur
during the build process:
If you generated source maps, open the folder specified in the outDir option and
you find the generated *.js file(s) along with the generated *js.map file(s).
NPM Task Runner - Adds support for npm scripts defined in package.json.
Supports yarn.
Webpack Task Runner - Adds support for webpack.
See also
Properties, React, Angular, Vue
Compile TypeScript code (ASP.NET Core)
Article • 05/26/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
You can add TypeScript support to your projects using the TypeScript SDK, available by
default in the Visual Studio installer or by using the NuGet package. For projects
developed in Visual Studio 2019 or later, we encourage you to use the TypeScript NuGet
package for greater portability across different platforms and environments.
For ASP.NET Core projects, one common usage for the NuGet package is to compile
TypeScript using the .NET Core CLI. Unless you manually edit your project file to import
build targets from a TypeScript SDK installation, the NuGet package is the only way to
enable TypeScript compilation using .NET Core CLI commands such as dotnet build and
dotnet publish . Also, for MSBuild integration with ASP.NET Core and TypeScript,
choose the NuGet package over the npm package.
If Visual Studio is installed, then the node.exe bundled with it will automatically be
picked up by Visual Studio. If you don't have Node.js installed, we recommend you
install the LTS version from the Node.js website.
2. In Solution Explorer (right pane). right-click the project node and choose Manage
NuGet Packages. In the Browse tab, search for Microsoft.TypeScript.MSBuild, and
then click Install on the right to install the package.
Visual Studio adds the NuGet package under the Dependencies node in Solution
Explorer. The following package reference gets added to your *.csproj file.
XML
<PackageReference Include="Microsoft.TypeScript.MSBuild"
Version="3.9.7">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers;
buildtransitive</IncludeAssets>
</PackageReference>
3. Right-click the project node and choose Add > New Item. Choose the TypeScript
JSON Configuration File, and then click Add.
If you don't see all the item templates, choose Show All Templates, and then
choose the item template.
Visual Studio adds the tsconfig.json file to the project root. You can use this file to
configure options for the TypeScript compiler.
4. Open tsconfig.json and update to set the compiler options that you want.
JSON
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"outDir": "wwwroot/js"
},
"include": [
"scripts/**/*"
]
}
In this example:
TypeScript
2. If you are using an older non-SDK style project, follow instructions in Remove
default imports before building.
Although the app builds automatically when you run it, we want to take a look at
something that happens during the build process:
If you generated source maps, open the folder specified in the outDir option and
you find the generated *.js file(s) along with the generated *js.map file(s).
4. If you want to compile every time you save the project, use the compileOnSave
option in tsconfig.json.
JSON
{
"compileOnSave": true,
"compilerOptions": {
}
}
For an example of using gulp with the Task Runner to build your app, see ASP.NET Core
and TypeScript .
If you run into issues where Visual Studio is using a version of Node.js or a third-party
tool that is different than what the version you expected, you may need to set the path
for Visual Studio to use. Choose Tools > Options. Under Projects and solutions, choose
Web Package Management > External Web Tools.
build folder
Two files are located in this folder. Both are entry points - for the main TypeScript
target file and props file respectively.
1. Microsoft.TypeScript.MSBuild.targets
This file sets variables that specify the run-time platform, such as a path to
TypeScript.Tasks.dll, before importing Microsoft.TypeScript.targets from the
tools folder.
2. Microsoft.TypeScript.MSBuild.props
tools folder
1. net45
2. netstandard1.3
3. tsc
This folder contains tsc.js , tsserver.js and all dependency files required to
run them as node scripts.
7 Note
If you are using the NuGet package for MSBuild support for a project, the project file
must not import Microsoft.TypeScript.Default.props or Microsoft.TypeScript.targets .
The files get imported by the NuGet package, so including them separately may cause
unintended behavior.
XML
<Import
Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStu
dioVersion)\TypeScript\Microsoft.TypeScript.Default.props"
Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$
(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props')"
/>
<Import
Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStu
dioVersion)\TypeScript\Microsoft.TypeScript.targets"
Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$
(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets')" />
Manage npm packages in Visual Studio
Article • 06/05/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
npm allows you to install and manage packages for use in both Node.js and ASP.NET
Core applications. Visual Studio makes it easy to interact with npm and issue npm
commands through the UI or directly. If you're unfamiliar with npm and want to learn
more, go to the npm documentation .
Visual Studio integration with npm is different depending on your project type.
) Important
npm expects the node_modules folder and package.json in the project root. If your
app's folder structure is different, you should modify your folder structure if you
want to manage npm packages using Visual Studio.
To open the package manager, from Solution Explorer, right-click the npm node in your
project.
Next, you can search for npm packages, select one, and install by selecting Install
Package.
Node.js projects
For Node.js projects (.njsproj), you can perform the following tasks:
Install packages from Solution Explorer
Manage installed packages from Solution Explorer
Use the .npm command in the Node.js Interactive Window
These features work together and synchronize with the project system and the
package.json file in the project.
Prerequisites
You need the Node.js development workload and the Node.js runtime installed to add
npm support to your project. For detailed steps, see Create a Node.js and Express app.
7 Note
For existing Node.js projects, use the From existing Node.js code solution template
or the Open folder (Node.js) project type to enable npm in your project.
In this window you can search for a package, specify options, and install.
Dependency type - Chose between Standard, Development, and Optional
packages. Standard specifies that the package is a runtime dependency, whereas
Development specifies that the package is only required during development.
Add to package.json - Recommended. This configurable option is deprecated.
Selected version - Select the version of the package you want to install.
Other npm arguments - Specify other standard npm arguments. For example, you
can enter a version value such as @~0.8 to install a specific version that is not
available in the versions list.
You can see the progress of the installation in the npm output in the Output window (to
open the window, choose View > Output or press Ctrl + Alt + O). This may take some
time.
Tip
You can search for scoped packages by prepending the search query with the
scope you're interested in, for example, type @types/mocha to look for TypeScript
definition files for mocha. Also, when installing type definitions for TypeScript, you
can specify the TypeScript version you're targeting by specifying a version, such as
@ts2.6 , in the npm argument field.
Package status
- Installed and listed in package.json
- Installed, but not explicitly listed in package.json
- Not installed, but listed in package.json
Install npm Package(s) Runs the npm install command to install the package
version listed in package.json. (Runs npm install .)
Update npm Package(s) Updates the package to the latest version, according to
the SemVer range specified in package.json. (Run npm update --save .) SemVer
ranges are typically specified using "~" or "^".
Uninstall npm Package(s) Uninstalls the package and removes it from package.json
(Runs npm uninstall --save .)
7 Note
In the window, you can use commands such as the following to install a package:
Tip
By default, npm will execute in your project's home directory. If you have multiple
projects in your solution specify the name or the path of the project in brackets.
.npm [MyProjectNameOrPath] install azure@4.2.3
Tip
If your project doesn't contain a package.json file, use .npm init -y to create a
new package.json file with default entries.
ASP.NET Core projects
For projects such as ASP.NET Core projects, you can integrate npm support in your
project and use npm to install packages.
7 Note
For ASP.NET Core projects, you can also use Library Manager or yarn instead of
npm to install client-side JavaScript and CSS files.
1. Right-click the solution and choose Manage NuGet packages. Search for npm and
choose Install to install npm.
2. To add the package.json file, right-click the project in Solution Explorer and choose
Add > New Item (or press Ctrl + SHIFT + A). Use the search box to find the npm
file, choose the npm Configuration File, use the default name, and click Add.
3. Include one or more npm packages in the dependencies or devDependencies
section of package.json. For example, you might add the following to the file:
JSON
"devDependencies": {
"gulp": "4.0.2",
"@types/jquery": "5.3.1"
}
When you save the file, Visual Studio adds the package under the Dependencies / npm
node in Solution Explorer. If you don't see the node, right-click package.json and
choose Restore Packages.
7 Note
In some scenarios, Solution Explorer may not show the correct status for installed
npm packages. For more information, see Troubleshooting.
When you save the file, Visual Studio adds the package under the Dependencies / npm
node in Solution Explorer. If you don't see the node, right-click package.json and
choose Restore Packages.
It may take several minutes to install a package. Check progress on package installation
by switching to npm output in the Output window.
In some scenarios, Solution Explorer may not show the correct status for installed
npm packages due to a known issue described here . For example, the package
may appear as not installed when it is installed. In most cases, you can update
Solution Explorer by deleting package.json, restarting Visual Studio, and re-adding
the package.json file as described earlier in this article. Or, when installing
packages, you can use the npm Output window to verify installation status.
In some ASP.NET Core scenarios, the npm node in Solution Explorer may not be
visible after you build the project. To make the node visible again, right-click the
project node and choose Unload Project. Then right-click the project node and
choose Reload Project.
If you see any errors when building your app or transpiling TypeScript code, check
for npm package incompatibilities as a potential source of errors. To help identify
errors, check the npm Output window when installing the packages, as described
previously in this article. For example, if one or more npm package versions has
been deprecated and results in an error, you may need to install a more recent
version to fix errors. For information on using package.json to control npm package
versions, see package.json configuration.
Develop JavaScript and TypeScript code
in Visual Studio without solutions or
projects
Article • 01/27/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
Starting in Visual Studio 2017, you can develop code without projects or solutions,
which enables you to open a folder of code and immediately start working with rich
editor support such as IntelliSense, search, refactoring, debugging, and more. In
addition to these features, the Node.js Tools for Visual Studio adds support for building
TypeScript files, managing npm packages, and running npm scripts.
To get started, select File > Open > Folder from the toolbar. Solution Explorer displays
all the files in the folder, and you can open any of the files to begin editing. In the
background, Visual Studio indexes the files to enable npm, build, and debug features.
Tip
Before using an Open Folder project, try creating a solution from existing Node.js
code. In some scenarios, this method provides better feature support in Visual
Studio. To create the project, choose File > New Project > JavaScript > From
Existing Node.js code, and then choose your project folder as the source.
Prerequisites
Visual Studio 2017 version 15.8 or later versions
Visual Studio Node.js development workload must be installed
npm integration
If the folder you open contains a package.json file, you can right-click package.json to
show a context menu (shortcut menu) specific to npm.
In the shortcut menu, you can manage the packages installed by npm in the same way
that you manage npm packages when using a project file.
In addition, the menu also allows you to run scripts defined in the scripts element in
package.json. These scripts will use the version of Node.js available on the PATH
environment variable. The scripts run in a new window. This is a great way to execute
build or run scripts.
package.json
If the package.json in the folder specifies a main element, the Debug command will be
available in the right-click shortcut menu for package.json. Clicking this will start
node.exe with the specified script as its argument.
JavaScript files
You can debug JavaScript files by right-clicking a file and selecting Debug from the
shortcut menu. This starts node.exe with that JavaScript file as its argument.
7 Note
If you don't see the Debug menu option, you may need to create the project from
existing Node.js code, as described previously.
7 Note
When building TypeScript code, we use the newest version installed in C:\Program
Files (x86)\Microsoft SDKs\TypeScript .
If there is a tsconfig.json file present in the folder, you can right-click a TypeScript file to
see a menu command to debug that TypeScript file. The option appears only if there is
no outFile specified in tsconfig.json. If an outFile is specified, you can debug that file
by right-clicking tsconfig.json and selecting the correct option. The tsconfig.json file
also gives you a build option to allow you to specify compiler options.
7 Note
You can find more information about tsconfig.json in the tsconfig.json TypeScript
Handbook page .
Unit Tests
You can enable the unit test integration in Visual Studio by specifying a test root in your
package.json:
JSON
{
// ...
"vsTest":{
"testRoot": "./tests"
}
// ...
}
The test runner enumerates the locally installed packages to determine which test
framework to use. If none of the supported frameworks are recognized, the test runner
defaults to ExportRunner. The other supported frameworks are:
Mocha (mochajs.org )
Jasmine (Jasmine.github.io )
Tape (github.com/substack/tape )
Jest (jestjs.io )
After opening Test Explorer (choose Test > Windows > Test Explorer), Visual Studio
discovers and displays tests.
7 Note
The test runner will only enumerate the JavaScript files in the test root, if your
application is written in TypeScript you need to build those first.
Create a Vue.js application using
Node.js Tools for Visual Studio
Article • 09/01/2022
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
Visual Studio supports app development with the Vue.js framework in either
JavaScript or TypeScript.
The following new features support Vue.js application development in Visual Studio:
) Important
Starting in Visual Studio 2022, you can alternatively create a Vue project using the
new CLI-based project type . The information in this article applies only to the
Node.js project type (.njsproj).
Prerequisites
You must have Visual Studio 2017 version 15.8 or a later version installed and the
Node.js development workload.
) Important
This article requires features that are only available starting in Visual Studio
2017 version 15.8.
If you need to install the workload but already have Visual Studio, go to Tools >
Get Tools and Features..., which opens the Visual Studio Installer. Choose the
Node.js development workload, then choose Modify.
To create the ASP.NET Core project, you must have the ASP.NET and web
development and .NET Core cross-platform development workloads installed.
You must have the Node.js runtime installed.
If you don't have it installed, install the LTS version from the Node.js website. In
general, Visual Studio automatically detects the installed Node.js runtime. If it
doesn't detect an installed runtime, you can configure your project to reference
the installed runtime in the properties page. (After you create a project, right-click
the project node and choose Properties).
) Important
These steps assume that you already have some experience with the Vue.js
framework. If not, please visit Vue.js to learn more about the framework.
In Visual Studio 2019, choose Create a new project in the start window. If the start
window isn't open, choose File > Start Window. Type web app, choose C# as the
language, then choose ASP.NET Core Empty, and then choose Next. On the next
screen, name the project client-app, and then choose Next.
Choose either the recommended target framework or .NET 6, and then choose
Create.
If you don't see the ASP.NET Core Web Application project template, you must
install the ASP.NET and web development workload and the .NET Core
development workload first. To install the workload(s), click the Open Visual Studio
Installer link in the left pane of the New Project dialog box (select File > New >
Project). The Visual Studio Installer launches. Select the required workloads.
Open the file ./Startup.cs, and add the following lines to the Configure method:
C#
2. Type vue init webpack client-app and follow steps when prompted to answer
additional questions.
7 Note
For .vue files, you need to use Webpack or a similar framework with a loader
to do the conversion. TypeScript and Visual Studio does not know how to
compile .vue files. The same is true for bundling; TypeScript doesn't know how
to convert ES2015 modules (that is, import and export statements) into a
single final .js file to load in the browser. Again, Webpack is the best choice
here. To drive this process from within Visual Studio using MSBuild, you need
to do start from a Visual Studio template. At present, there is no ASP.NET
template for Vue.js development in-the-box.
JavaScript
// Paths
assetsRoot: path.resolve(__dirname, '../../wwwroot'),
Indicate the project to build the client app each time that a build is
triggered
1. In Visual Studio, go to Project > Properties > Build Events.
2. On Pre-build event command line, type npm --prefix ./client-app run build .
JavaScript
devtoolModuleFilenameTemplate: '[absolute-resource-path]',
devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?
[hash]'
1. Go to your command prompt and change the current directory to the project root
folder.
2. Type vue create client-app , and then choose Manually select features.
By setting this option, you avoid cluttering your project each time that you build in
Visual Studio.
2. Next, create a vue.config.js file in ./client-app/ and add the following code.
JavaScript
module.exports = {
outputDir: '../wwwroot',
configureWebpack: {
output: {
devtoolModuleFilenameTemplate: '[absolute-resource-path]',
devtoolFallbackModuleFilenameTemplate: '[absolute-resource-
path]?[hash]'
}
}
};
The preceding code configures Webpack and sets the wwwroot folder.
Alternatively, you can build the vue-cli 3.0 project as a pre-build event using the
ASP.NET project properties. Right-click the project, choose Properties, and include the
following commands in the Build tab, in the Pre-build event command line text box.
cd ./client-app
npm run build
cd ../
Limitations
lang attribute only supports JavaScript and TypeScript languages. The accepted
Debugging script blocks in .vue files isn't supported due to its preprocessed
nature.
TypeScript doesn't recognize .vue files as modules. You need a file that contains
code such as the following to tell TypeScript what .vue files look like (vue-cli 3.0
template already includes this file).
JavaScript
// ./client-app/vue-shims.d.ts
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
Running the command npm run build as a pre-build event on the project
properties doesn't work when using vue-cli 3.0.
See also
Vue get started guide .
Vue CLI project .
Webpack configuration documentation .
Work with the Node.js interactive
window
Article • 04/30/2022
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
Node.js Tools for Visual Studio include an interactive window for the installed Node.js
runtime. This window allows you to enter JavaScript code and see the results
immediately, as well as execute npm commands to interact with the current project. The
interactive window is also known as a REPL (Read/Evaluate/Print Loop).
The default short-cut keys to open the Node.js interactive window are [CTRL] + K, N. Or,
you can open the window from the toolbar by choosing View > Windows > Node.js
Interactive Window.
.cls, .clear Clears the contents of the editor window, leaving the history and execution
context intact.
.help Displays help on the specified command, or on all available commands and key
bindings if none is specified.
.npm Runs an npm command. If the solution contains more than one project, specify
the target project using .npm [projectname] <npm arguments> .
.reset Resets the execution environment to the initial state, keep history.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
You can debug JavaScript and TypeScript code using Visual Studio. You can hit
breakpoints, attach the debugger, inspect variables, view the call stack, and use other
debugging features.
Tip
If you haven't already installed Visual Studio, go to the Visual Studio downloads
page to install it for free. If you are developing Node.js applications, you need to
install the Node.js development workload with Visual Studio.
Breakpoints are the most basic and essential feature of reliable debugging. A
breakpoint indicates where Visual Studio should suspend your running code, so
you can look at the values of variables or the behavior of memory, or whether or
not a branch of code is getting run.
The debugger pauses at the breakpoint you set (IDE highlights the statement in
the yellow background). Now, you can inspect your app state by hovering over
variables currently in scope, using debugger windows like the Locals and Watch
windows.
4. If you want to use the Chrome Developer Tools, press F12 in the Chrome browser.
Using these tools, you can examine the DOM or interact with the app using the
JavaScript Console.
For debugging client-side script in ASP.NET apps, choose Tools > Options >
Debugging, and then select Enable JavaScript Debugging for ASP.NET (Chrome,
Edge, and IE).
For more detailed information, see the blog post Debug JavaScript in Microsoft
Edge and this post for Google Chrome . For debugging TypeScript in ASP.NET
Core, see Create an ASP.NET Core app with TypeScript.
For Node.js applications and other JavaScript projects, follow the steps described
here.
7 Note
For ASP.NET and ASP.NET Core, debugging embedded scripts in .CSHTML files is
not supported. JavaScript code must be in separate files to enable debugging.
For help with generating source maps, see Generate source maps for debugging.
Other browser instances can prevent the browser from opening with debugging
enabled. (Browser extensions may be running and intercept full debug mode, so
you may need to open Task Manager to find and close unexpected instances of
Chrome.)
For best results, shut down all instances of Chrome, even if you're working with
Microsoft Edge (Chromium). Both the browsers use the same chromium code base.
Starting in Visual Studio 2019, you can set the --remote-debugging-port=9222 flag
at browser launch by selecting Browse With... > from the Debug toolbar.
If you don't see the Browse With... command in the Debug toolbar, select a
different browser, and then retry.
From the Browse With dialog box, choose Add, and then set the flag in the
Arguments field. Use a different friendly name for the browser, like Edge with
Debugging or Chrome with Debugging. For details, see the Release Notes.
Alternatively, open the Run command from the Windows Start button (right-click
and choose Run), and enter the following command:
msedge --remote-debugging-port=9222
or,
chrome.exe --remote-debugging-port=9222
The app isn't yet running, so you get an empty browser page.
1. Switch to Visual Studio and then set a breakpoint in your source code, which might
be a JavaScript file, TypeScript file, or a JSX file. (Set the breakpoint in a line of code
that allows breakpoints, such as a return statement or a var declaration.)
To find the specific code in a transpiled file, use Ctrl+F (Edit > Find and Replace >
Quick Find).
For client-side code, to hit a breakpoint in a TypeScript file, .vue, or JSX file typically
requires the use of source maps. A source map must be configured correctly to
support debugging in Visual Studio.
2. Select your target browser as the debug target in Visual Studio, then press Ctrl+F5
(Debug > Start Without Debugging) to run the app in the browser.
If you created a browser configuration with a friendly name, choose that as your
debug target. The app opens in a new browser tab.
Tip
Starting in Visual Studio 2017, after you attach to the process the first time by
following these steps, you can quickly reattach to the same process by
choosing Debug > Reattach to Process.
4. In the Attach to Process dialog, get a filtered list of browser instances that you can
attach to. Choose the correct debugger for your target browser, JavaScript
(Chrome) or JavaScript (Microsoft Edge - Chromium) in the Attach to field, type
chrome or edge in the filter box to filter the search results.
5. Select the browser process with the correct host port (localhost in this example),
and select Attach.
The port (for example, 1337) may also appear in the Title field to help you select
the correct browser instance.
The following example shows how this looks for the Microsoft Edge (Chromium)
browser.
Tip
If the debugger does not attach and you see the message "Failed to launch
debug adapter" or "Unable to attach to the process. An operation is not legal
in the current state.", use the Windows Task Manager to close all instances of
the target browser before starting the browser in debugging mode. Browser
extensions may be running and preventing full debug mode.
6. The code with the breakpoint may have already been executed, refresh your
browser page. If necessary, take action to cause the code with the breakpoint to
execute.
While paused in the debugger, you can examine your app state by hovering over
variables and using debugger windows. You can advance the debugger by
stepping through code (F5, F10, and F11). For more information on basic
debugging features, see First look at the debugger.
You may hit the breakpoint in either a transpiled .js file or source file, depending
on your app type, which steps you followed previously, and other factors such as
your browser state. Either way, you can step through code and examine variables.
If you need to break into code in a TypeScript, JSX, or .vue source file and are
unable to do it, make sure that your environment is set up correctly, as
described in the Troubleshooting section.
If you need to break into code in a transpiled JavaScript file (for example,
app-bundle.js) and are unable to do it, remove the source map file,
filename.js.map.
Close all browser instances, including Chrome extensions (using the Task Manager),
so that you can run the browser in debug mode.
Make sure that your source map file includes the correct relative path to your
source file and that it doesn't include unsupported prefixes such as webpack:///,
which prevents the Visual Studio debugger from locating a source file. For
example, a reference like webpack:///.app.tsx might be corrected to ./app.tsx. You
can do this manually in the source map file (which is helpful for testing) or through
a custom build configuration. For more information, see Generate source maps for
debugging.
Alternatively, if you need to break into code in a source file (for example, app.tsx) and
are unable to do it, try using the debugger; statement in the source file, or set
breakpoints in the Chrome Developer Tools (or F12 Tools for Microsoft Edge) instead.
A TypeScript project in Visual Studio generates source maps for you by default. For
more information, see Configure source maps using a tsconfig.json file.
In a JavaScript project, you can generate source maps using a bundler like
webpack and a compiler like the TypeScript compiler (or Babel), which you can add
to your project. For the TypeScript compiler, you must also add a tsconfig.json file
and set the sourceMap compiler option. For an example that shows how to do this
using a basic webpack configuration, see Create a Node.js app with React.
7 Note
If you are new to source maps, read Introduction to JavaScript Source Maps
before continuing.
To configure advanced settings for source maps, use either a tsconfig.json or the project
settings in a TypeScript project, but not both.
To enable debugging using Visual Studio, you need to make sure that the reference(s) to
your source file in the generated source map are correct (this may require testing). For
example, if you're using webpack, references in the source map file include the
webpack:/// prefix, which prevents Visual Studio from finding a TypeScript or JSX source
file. Specifically, when you correct this for debugging purposes, the reference to the
source file (such as app.tsx), must be changed from something like webpack:///./app.tsx
to something like ./app.tsx, which enables debugging (the path is relative to your source
file). The following example shows how you can configure source maps in webpack,
which is one of the most common bundlers, so that they work with Visual Studio.
(Webpack only) If you're setting the breakpoint in a TypeScript of JSX file (rather than a
transpiled JavaScript file), you need to update your webpack configuration. For example,
in webpack-config.js, you might need to replace the following code:
JavaScript
output: {
filename: "./app-bundle.js", // This is an example of the filename in
your project
},
JavaScript
output: {
filename: "./app-bundle.js", // Replace with the filename in your
project
devtoolModuleFilenameTemplate: '[resource-path]' // Removes the
webpack:/// prefix
},
This is a development-only setting to enable debugging of client-side code in Visual
Studio.
For complicated scenarios, the browser tools (F12) sometimes work best for debugging,
because they don't require changes to custom prefixes.
JSON
{
"compilerOptions": {
"noImplicitAny": false,
"module": "commonjs",
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5"
},
"exclude": [
"node_modules"
]
}
inlineSourceMap: Emit a single file with source maps instead of creating a separate
source map for each source file.
inlineSources: Emit the source alongside the source maps within a single file;
requires inlineSourceMap or sourceMap to be set.
mapRoot: Specifies the location where the debugger should find source map
(.map) files instead of the default location. Use this flag if the run-time .map files
need to be in a different location than the .js files. The location specified is
embedded in the source map to direct the debugger to the location of the .map
files.
sourceMap: Generates a corresponding .map file.
sourceRoot: Specifies the location where the debugger should find TypeScript files
instead of the source locations. Use this flag if the run-time sources need to be in a
different location than the location at design-time. The location specified is
embedded in the source map to direct the debugger to where the source files are
located.
For more details about the compiler options, check the page Compiler Options on the
TypeScript Handbook.
However, you can't automatically hit breakpoints on files generated with Razor syntax
(cshtml, vbhtml). There are two approaches you can use to debug this kind of file:
Place the debugger; statement where you want to break: This statement causes
the dynamic script to stop execution and start debugging immediately while it's
being created.
Load the page and open the dynamic document on Visual Studio: You'll need to
open the dynamic file while debugging, set your breakpoint, and refresh the page
for this method to work. Depending on whether you're using Chrome or Microsoft
Edge (Chromium), you'll find the file using one of the following strategies:
7 Note
When using Chrome, you might get a message "no source is available
between <script> tags". It's OK, just continue debugging.
See also
Properties, React, Angular, Vue
Unit testing JavaScript and TypeScript in
Visual Studio
Article • 06/05/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
You can write and run unit tests in Visual Studio using some of the more popular
JavaScript frameworks without the need to switch to a command prompt. Both Node.js
and ASP.NET Core projects are supported.
Mocha (mochajs.org )
Jasmine (Jasmine.github.io )
Tape (github.com/substack/tape )
Jest (jestjs.io )
Export Runner (this framework is specific to Node.js Tools for Visual Studio)
If your favorite framework is not supported, see Add support for a unit test framework
for information on adding support.
The Node.js development workload is required to support unit testing for CLI-based
projects.
Mocha and Tape test libraries are also supported. To use one of these, simply change the
default test library in package.json to the appropriate test library’s package.
Use the NuGet package to add TypeScript support instead of the npm TypeScript
package.
3. In Solution Explorer, right-click the project node and choose Unload Project.
4. Add the following elements to the .csproj file in the PropertyGroup element.
This example specifies Mocha as the test framework. You could specify Jest, Tape,
or Jasmine instead.
XML
<PropertyGroup>
...
<JavaScriptTestRoot>tests\</JavaScriptTestRoot>
<JavaScriptTestFramework>Mocha</JavaScriptTestFramework>
<GenerateProgramFile>false</GenerateProgramFile>
</PropertyGroup>
The JavaScriptTestRoot element specifies that your unit tests will be in the tests
folder of the project root.
5. In Solution Explorer, right-click the project node and choose Reload Project.
6. Add npm support as described in the npm package management article under
ASP.NET Core projects.
This requires installing the Node.js runtime for npm support and adding
package.json in the project root.
JSON
"dependencies": {
"mocha": "8.3.0",
Some unit testing frameworks, such as Jest, require additional npm packages. For
Jest, use the following JSON:
JSON
"dependencies": {
"jest": "26.6.3",
"jest-editor-support": "28.1.0"
7 Note
In some scenarios, Solution Explorer may not show the npm node due to a
known issue described here . If you need to see the npm node, you can
unload the project (right-click the project and choose Unload Project) and
then reload the project to make the npm node re-appear.
If you are using the example described in Create an ASP.NET Core app with
TypeScript, add the following code at the end of the library.ts file, which is in the
scripts folder.
TypeScript
function getData(value) {
if (value > 1) {
return true;
}
}
module.exports = getData;
For TypeScript, unit tests are run against the generated JavaScript code.
9. Add your unit tests to the tests folder in the project root.
For example, you might use the following code by selecting the correct
documentation tab that matches your test framework, in this example either
Mocha or Jest. This code tests a function called getData .
Mocha
TypeScript
const getData = require('../wwwroot/js/library.js');
var assert = require('assert');
10. Open Test Explorer (choose Test > Windows > Test Explorer) and Visual Studio
discovers and displays tests. If tests are not showing initially, then rebuild the
project to refresh the list.
7 Note
For TypeScript, do not use the outfile option in tsconfig.json, because Test
Explorer won't be able to find your unit tests. You can use the outdir option,
but make sure that configuration files such as package.json and
tsconfig.json are in the project root.
For TypeScript, unit tests are run against the generated JavaScript code.
7 Note
In most TypeScript scenarios, you can debug a unit test by setting a breakpoint in
TypeScript code, right-clicking a test in Test Explorer, and choosing Debug. In more
complex scenarios, such as some scenarios that use source maps, you may have
difficulty hitting breakpoints in TypeScript code. As a workaround, try using the
debugger keyword.
7 Note
7 Note
<VisualStudioFolder>\Common7\IDE\Extensions\Microsoft\NodeJsTools\TestAdapter\TestF
rameworks
If you don't see the NodeJsTools folder in an ASP.NET Core project, add the Node.js
development workload using the Visual Studio Installer. This workload includes support
for unit testing JavaScript and TypeScript.
This folder has to contain a JavaScript file with the same name which exports the
following two functions:
find_tests
run_tests
For a good example of the find_tests and the run_tests implementations, see the
implementation for the Mocha unit testing framework in:
<VisualStudioFolder>\Common7\IDE\Extensions\Microsoft\NodeJsTools\TestAdapter\TestF
rameworks\mocha\mocha.js
To enable this, right-click the project node in the Solution Explorer, choose Unload
Project, and then choose Edit Project. Then in the project file, add the following two
elements to a property group.
) Important
Make sure that the property group you're adding the elements to doesn't have a
condition specified. This can cause unexpected behavior.
XML
<PropertyGroup>
<JavaScriptTestRoot>tests\</JavaScriptTestRoot>
<JavaScriptTestFramework>Tape</JavaScriptTestFramework>
</PropertyGroup>
Next, add your tests to the test root folder you specified, and they will be available to
run in the Test Explorer window. If they don't initially appear, you may need to rebuild
the project.
XML
<PropertyGroup>
<GenerateProgramFile>false</GenerateProgramFile>
</PropertyGroup>
Some test frameworks may require additional npm packages for test detection. For
example, jest requires the jest-editor-support npm package. If necessary, check the
documentation for the specific framework.
The preferred way to add unit tests to your project is by creating a tests folder in your
project, and setting that as the test root in project properties. You also need to select
the test framework you want to use.
You can add simple blank tests to your project, using the Add New Item dialog box.
Both JavaScript and TypeScript are supported in the same project.
For a Mocha unit test, use the following code:
JavaScript
If you haven't set the unit test options in the project properties, you must ensure the
Test Framework property in the Properties window is set to the correct test framework
for your unit test files. This is done automatically by the unit test file templates.
7 Note
The unit test options will take preference over the settings for individual files.
After opening Test Explorer (choose Test > Windows > Test Explorer), Visual Studio
discovers and displays tests. If tests are not showing initially, then rebuild the project to
refresh the list.
7 Note
For TypeScript, do not use the outdir or outfile option in tsconfig.json, because
Test Explorer won't be able to find your unit tests.
For TypeScript, unit tests are run against the generated JavaScript code.
7 Note
In most TypeScript scenarios, you can debug a unit test by setting a breakpoint in
TypeScript code, right-clicking a test in Test Explorer, and choosing Debug. In more
complex scenarios, such as some scenarios that use source maps, you may have
difficulty hitting breakpoints in TypeScript code. As a workaround, try using the
debugger keyword.
7 Note
7 Note
If you get an error indicating that vstest.console.exe cannot be found, make sure
you've opened the Developer Command Prompt and not a regular command
prompt.
Property pages for React, Angular, and
Vue projects in Visual Studio
Article • 06/29/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
This article applies to React, Angular, and Vue projects created in Visual Studio that use
the .esproj project format. This format is supported starting in Visual Studio 2022.
The Property Pages provides access to project settings. To open the property pages,
select the project in Solution Explorer and then select the Properties icon, or right-click
the project and select Properties.
7 Note
Your computer might show different names or locations for some of the Visual
Studio user interface elements in this article. You may be using a different edition of
Visual Studio or different environment settings. For more information, see
Personalize the IDE.
Build tab
Under the General tab, the following properties are available.
Build Command
Specifies the command to run when you build the project. (Build > Build Solution, or
when you run the project.) If used, this is typically an npm command.
Specifies the command to run when you build the project, when the project is
integrated with the ASP.NET Core Web API project. Generates production-ready files. By
default, this command is npm run build .
Specifies the output folder for production build objects when the Production Build
Command is used.
Clean Command
Specifies the command to run when you clean the project. (Build > Clean Solution) If
used, this is typically an npm command.
Working Directory
Specifies the working directory for the build command. This is the project root, by
default.
Deploy tab
Startup Command
Specifies the command to execute when you start the project. For example, an Angular
project uses npm start by default.
Working Directory
Specifies the working directory for the startup command. By default, this is the project
root. Relative paths are relative to the project root.
7 Note
In Visual Studio, launch.json stores the startup settings associated with the Start
button in the Debug toolbar. Currently, launch.json must be located under the
.vscode folder.
See also
JavaScript and TypeScript in Visual Studio
package.json configuration
Article • 04/30/2022
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
If you are developing a Node.js app with a lot of npm packages, it's not uncommon to
run into warnings or errors when you build your project if one or more packages has
been updated. Sometimes, a version conflict results, or a package version has been
deprecated. Here are a couple of quick tips to help you configure your package.json
file and understand what is going on when you see warnings or errors. This is not a
complete guide to package.json and is focused only on npm package versioning.
The npm package versioning system has strict rules. The version format follows here:
[major].[minor].[patch]
Let's say you have a package in your app with a version of 5.2.1. The major version is 5,
the minor version is 2, and the patch is 1.
In a major version update, the package includes new features that are backwards-
incompatible, that is, breaking changes.
In a minor version update, new features have been added to the package that are
backwards-compatible with earlier package versions.
In a patch update, one or more bug fixes are included. Bug fixes are always
backwards-compatible.
It's worth noting that some npm package features have dependencies. For example, to
use a new feature of the TypeScript compiler package (ts-loader) with webpack, it is
possible you would also need to update the webpack npm package and the webpack-cli
package.
To help manage package versioning, npm supports several notations that you can use in
the package.json. You can use these notations to control the type of package updates
that you want to accept in your app.
Let's say you are using React and need to include the react and react-dom npm
package. You could specify that in several ways in your package.json file. For example,
you can specify use of the exact version of a package as follows.
JSON
"dependencies": {
"react": "16.4.2",
"react-dom": "16.4.2",
},
Using the preceding notation, npm will always get the exact version specified, 16.4.2.
You can use a special notation to limit updates to patch updates (bug fixes). In this
example:
JSON
"dependencies": {
"react": "~16.4.2",
"react-dom": "~16.4.2",
},
you use the tilde (~) character to tell npm to only update a package when it is patched.
So, npm can update react 16.4.2 to 16.4.3 (or 16.4.4, etc.), but it will not accept an
update to the major or minor version. So, 16.4.2 will not get updated to 16.5.0.
You can also use the caret (^) symbol to specify that npm can update the minor version
number.
JSON
"dependencies": {
"react": "^16.4.2",
"react-dom": "^16.4.2",
},
Using this notation, npm can update react 16.4.2 to 16.5.0 (or 16.5.1, 16.6.0, etc.), but it
will not accept an update to the major version. So, 16.4.2 will not get updated to 17.0.0.
When npm updates packages, it generates a package-lock.json file, which lists the actual
npm package versions used in your app, including all nested packages. While
package.json controls the direct dependencies for your app, it does not control nested
dependencies (other npm packages required by a particular npm package). You can use
the package-lock.json file in your development cycle if you need to make sure that other
developers and testers are using the exact packages that you are using, including nested
packages. For more information, see package-lock.json in the npm documentation.
For Visual Studio, the package-lock.json file is not added to your project, but you can
find it in the project folder.