📜 ⬆️ ⬇️

Creating a minimal ASP.NET Core web application with support for npm, Webpack and TypeScript in Visual Studio 2017

Introduction


I’m writing this tutorial primarily for myself, in order to be able to quickly create a minimal application with support for npm, Webpack and TypeScript based on the initial template of an ASP.NET Core application (which will have debugging from Visual Studio).


Motivation


I am rather new to web and in particular javascript. However, I work with .Net constantly. I also believe that knowing JavaScript and all sorts of different frameworks on it, which is now like dirt, is stylish, fashionable and youthful. But in order to feel the next libu, you usually need to install a lot of things to make it work in principle.


Usually, a server (via node.js), npm, and something like a Webpack is required (for Less to work or for some template / minifier). I picked ASP.NET for a bit (Not Core, but normal) and roughly imagine how to deal with the server part, but for me the frontend is a dark forest.


The problem is that technologies on the web usually do not focus on ASP.NET, but more on node.js, php and other mainstream. And the examples in the documentation are also always based on this all, and for the person of the uninitiated, it’s not so fast that it all works out from scratch to be configured for ASP.NET.


In this tutorial, I show how, step by step, from a template new project on ASP.NET Core make a minimal working application in which



Knowing how to quickly create such an application, you can then safely study any web technologies (including npm, Webpack and TypeScript itself), and the server will be in its native dotnet.


Currently ASP.NET already has mechanisms built in similar to those in the Webpack, and the studio out of the box (at least 2017) works with TypeScript and compiles it automatically if you create a config file for the TypeScript compiler but.
But all these things are supported by the ASP.NET developers, not the web community.


The standard TypeScript compiler in this tutorial is disabled, and one that is a module for npm is used.


Training


What you need to download and install to get started



Project creation


Open Visual Studio, create a new project using the standard ASP.NET Core Web Application template (.NET Core) . The template is in Templates - Visual C # - Web . If there is no such template, some components may not be installed (You need to run the Visual Studio installer again and install them).


Now we have a start project, it should be compiled and run.


If git is used, then immediately add the .gitignore file to the folder with the solution ( Initially, we initialize the git repository). The .gitignore file for solutions in Visual Studio can be obtained from here .


View full code


Simplify the typical project


Next, change the project so that it turned out as simple as possible.
Let's make Hello World out of it.


Delete the following files



In the Controllers / HomeController.cs file in the HomeController class
replace the insides with the following code


 public IActionResult Index() => View(); public string Error() => "Error"; 

In fact, everything except the Index() and Error() methods is removed here, while Error() now returns the string "Error" instead of the view (as we previously deleted the file with this view).


The final touch - we replace the contents of the Views / Home / Index.cshtml file with the following


 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Index</title> </head> <body> <h1>Hello world</h1> </body> </html> 

That's it, now we have a basic, maximally simplified project. It can be compiled and run, the page will display the text "Hello world"


View full code


Add npm


Add package.json file to the project


 { "version": "1.0.0", "name": "yourappname", "private": true } 

Instead of "yourappname" enter the name of the project in small letters.


npm with its work can write to the log with the name npm-debug.log . It is necessary to exclude him from the project, so as not to interfere. This can be done either by calling the context menu on the studio and selecting Exclude From Project . Or, if it has not been created yet (most likely, it is so), you can edit the project file .csproj , by adding the following to the <Project> tag


 <ItemGroup> <None Remove="npm-debug.log" /> </ItemGroup> 

Everything, now we have support for npm, in the project dependencies the studio now shows the node "npm".


If you build a project (As well as when you open the project, change the package.json file, etc.), the process of restoring the npm dependencies will start if they are specified (They are not available now). Dependencies are downloaded to the node_modules folder in the project folder (Studio does not perceive this folder as part of the project).


View full code


Add Webpack


Webpack is a npm dependency, so you need to add it to package.json as a dependency. Since it will not be used in client-side JavaScript code, it is declared as dev dependency . For us, this means that it will work as an additional compilation tool for Visual Studio, neither on the server nor on the client, on the client there will be that content (including JavaScript code) that Webpack will generate.


In addition to the Webpack itself, two things that will facilitate the work will also be needed (However, they are not required)



First, download and install the extension for Visual Studio, you can find it by the name "NPM Task Runner", or download this link .


Now add the following lines to package.json (add inside the bracelets)


 "devDependencies": { "webpack": "^2.5.1", "clean-webpack-plugin": "^0.1.16" }, "scripts": { "webpack-script": "webpack" }, "-vs-binding": { "BeforeBuild": [ "webpack-script" ] } 

In "devDependencies" we specified the Webpack itself and the plugin to clean up what it generates.


In the "scripts" we specified a script called "webpack-script" , which will launch the Webpack (At this point it will generate content, translate the code, etc.). The Visual Studio extension that we installed earlier makes it possible for the studio to see this script as a task that can be performed, so we can schedule this task to be executed when building the application.


In "-vs-binding" we indicated that Visual Studio should invoke the "webpack-script" task (which the studio now sees thanks to the installed extension) every time before building the project.


Now you need to configure the Webpack itself. It is configured using the webpack.config.js javascript script, which will be executed via node.js at the time of the webpack-script task call. Add the webpack.config.js file to the project and fill its contents with the following code


 "use strict" { //     output  let path = require('path'); //      (bundle)    const CleanWebpackPlugin = require('clean-webpack-plugin'); //     const bundleFolder = "wwwroot/bundle/"; module.exports = { //     entry: "./Scripts/main.js", //   output: { filename: 'script.js', path: path.resolve(__dirname, bundleFolder) }, plugins: [ new CleanWebpackPlugin([bundleFolder]) ] }; } 

Here we set up the input and output paths to the JavaScript files, as well as prescribed a previously added plugin to clear the output folder.


The output file webpack generates based on the input. We do not have an input file yet, so we need to create it. Create a Scripts / main.js file with the following contents.


 document.getElementById("helloworld").innerText = "Hello world from script"; 

The input file will not be available to the user, as it is located in the Scripts folder, not wwwroot , the output file generated by the Webpack will go to the wwwroot / bundle / folder and will be available to the client.


On the client side, the output file will be located at ~ / bundle / script.js , where ~ is the address of the site where the web application is running.
Modify the Views / Home / Index.cshtml file so that it includes the output file, and so that the script can change the text on the page (by the id of the "helloworld" element).
To do this, replace the insides of the <body> with the following


 <h1 id="helloworld"></h1> <script src="~/bundle/script.js"></script> 

In case git is used, the files generated by the Webpack should also be excluded. To do this, create another .gitignore file, but now in the project folder (Not to be confused with the solution folder)


 #  webpack-  wwwroot/bundle/ 

The studio will show the .gitignore file in the project so that this does not happen, in the project file .csproj you need to add the following lines inside the root <Project> (Well, or via the context menu on the file -> Exclude From Project )


 <ItemGroup> <None Remove=".gitignore" /> </ItemGroup> 

Everything, now the project is completely configured under use of npm and Webpack. If you compile and run the application, the page should display the text "Hello world from script"


At this stage, you can already install JavaScript libraries by declaring them in the "dependencies" section of package.json and using them in Scripts / main.js , connecting these libraries as modules through the require(" ") function require(" ") . For example, if you install the jquery library in this way, the Scripts / main.js file can be rewritten as follows (Note: this is just an example, to continue, it is not necessary either to install jquery or change main.js )


 var $ = require('jquery'); $("#helloworld").text("Hello world"); 

The only thing that debugging by input files in Visual Studio will not work. However, this can be fixed by adding TypeScript support.


View full code


Add TypeScript


First of all, you need to disable the standard TypeScript transfiguration. To do this, add the following lines in the <Project> root tag in the project file .csproj


 <PropertyGroup> <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked> </PropertyGroup> 

Next, you need to add TypeScript as dev dependency for npm. To do this "devDependencies" add the following to the package.json file in the "devDependencies" section


 "typescript": "^2.3.2", "ts-loader": "^2.0.3" 

Now you need to create a configuration file for the TypeScript compiler. Create a tsconfig.json file with the following content


 { "compilerOptions": { "noImplicitAny": false, "noEmitOnError": true, "removeComments": false, "alwaysStrict": true, "allowSyntheticDefaultImports": true, "lib": [ "dom", "es5", "es2015.promise" ], "allowJs": true, "target": "es5", "module": "es2015", "moduleResolution": "node", "sourceMap": true }, "include": [ "./Scripts/*" ], "compileOnSave": false } 

Description of some of the values ​​specified in this file



Next you need to make TypeScript friends with Webpack. To do this, replace the script file to configure the Webpack configuration and webpack.config.js with the following (In fact, we change some places, but in order not to write all the changes, I post the full file)


 "use strict" { //     output  let path = require('path'); //      (bundle)    const CleanWebpackPlugin = require('clean-webpack-plugin'); //     const bundleFolder = "wwwroot/bundle/"; module.exports = { //     entry: "./Scripts/main.ts", //   output: { filename: 'script.js', path: path.resolve(__dirname, bundleFolder) }, module: { rules: [ { test: /\.tsx?$/, loader: "ts-loader", exclude: /node_modules/, }, ] }, resolve: { extensions: [".tsx", ".ts", ".js"] }, plugins: [ new CleanWebpackPlugin([bundleFolder]) ], //        // (     ) devtool: "inline-source-map" }; } 

Here we changed the extension of the input script from .js to .ts , indicated that the input script needs to be passed through the TypeScript loader: "ts-loader" ( loader: "ts-loader" ) and did some other things.


And the last step is to rename the input script file from Scripts / main.js to Scripts / main.ts , the insides can be left unchanged .


View full code


Total


Everything! Now we have a working project on ASP.NET Core, which has npm, Webpack and TypeScript and it all works in one bundle.


Also, the TypeScript debugging from Visual Studio is now available, you can set a breakpoint in the input .ts file, run the project in debug mode (You need to start it in browsers chrome or internet explorer, otherwise debugging will not work, also in chrome it works for me only when I, after loading the page, clearly press the refresh of the page, apparently the debugger does not connect to the chrome immediately. At the same time, please note that breakpoints are set in the input files, but the actual code works output (In the output code, in the form of a comment webpack records the information needed for mapping from the output to the input files).


You can create other input files in the Scripts folder, in the form of .ts or .js, and both of them will fully support the new EcmaScript standard (The output file will be the es5 standard). To connect additional input files, you need to arrange them in the form of modules and connect them to main.ts via the import statement or the require() function.


Another small note is that the output files (those in the wwwroot / bundle / folder) should not be excluded from the project via the .csproj file, since if the studio does not see them, debugging of the input files stops working.


')

Source: https://habr.com/ru/post/328638/


All Articles