Using TypeScript with Webpack in Asp.Net MVC

By   Calendar icon Mar 20, 2020   Level 1 icon

Description:

Here we explain what the JavaScript Knockout library is for and how to use it in the framework ASP.NET MVC. We give some examples of using Knockout.

Preferencesoft

Webpack is a JavaScript web application development tool that automates certain tasks, including module packaging.

It determines the dependencies of source files and generates one or more blunder module.
With loaders, Webpack also supports TypeScript and .tsx files.

It is often used to create React, Angular and Vue applications.
But it can help create a front-end TypeScript app that can be integrated into a Razor page.

JavaScript applications are becoming more and more complex and can use many modules or reference a multitude of style sheets. To optimize an application, it's best not to incorporate unused modules or to include the same modules multiple times and not have a final application made up of many files, which slows down the application's loading.
It is better to make optimal cutting of the modules and group all the files into one. Webpack supports all these optimization tasks and frees up the developer who can then focus on the essentials: implementing his application.

There are tools available under Visual Studio to optimize assets, to minify and group sources.
Some are pre-installed when creating an application ASP.NET MVC others are installable with tasks like Gulp or Grunt.

Webpack performs almost the same tasks but in a more centralized way and gives the ability to test an application with its local server.
However, Webpack does not automatically integrate the application into a ASP.NET page and makes the links between the application and the code on the page quite complicated.

Webpack is very used by those who program with React, but we will use it to create and test a TypeScript application without a library.

Installation of Webpack

Let's create ASP.NET MVC application and create a package.json file if it hasn't already been created.

In the CMD command shell, let's go in the main directory of the project and let's type

npm init

by answering the questions asked.

And let's put the following code:

{
  "name": "preferencesoft",
  "version": "1.0.0",
  "description": "Webpack ASP.NET",
  "private": true,
  "dependencies": {},
  "devDependencies": {
    "path": "0.12.7",
    "html-webpack-plugin": "3.2.0",
    "webpack": "4.42.0",
    "webpack-cli": "3.3.11",
    "webpack-dev-server": "3.10.0",
    "typescript": "3.8.3",
    "ts-loader": "5.2.1"
  },
  "scripts": {
    "start": "webpack-dev-server --config ./webpack.config.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "J.-C. C.",
  "license": "ISC"
}

By saving the file, Visual Studio installs all packages.
Otherwise, type the command:

npm install

Let's create a JavaScript file named in the main directory containing:

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

// Host
const host = process.env.HOST || 'localhost';


module.exports = {

    // Building mode
    mode: 'development',

    // Entry point of the application
    entry:'./src/main.ts',

    output: {
        // Target application
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },

    module: {
        rules: [
            {
                    test: /\.(ts|tsx)$/,
                    exclude: /node_modules/,
                    loader: 'ts-loader'
            }
        ]
    },

    plugins: [
        // Re-generate index.html with injected script tag.
        new HtmlWebpackPlugin({
            inject: true,
            template: 'dist/index.html'
        })
    ],

    devServer: {
  
        // Serve index.html as the base
        contentBase: path.resolve(__dirname, 'dist'),


        // Enable compression
        compress: true,

        // Enable hot reloading
        hot: true,
        host,
        port: 8000,

        // Public path is root of content base
        publicPath: '/',

        proxy: {
            '/api': {
		target: "http://localhost:8000",
                bypass: (req, res) => res.send({
                    mssg: 'proxy server <from bypass in webpack>'
                })
            }
        }
    }
};

In the main file of the project create with the command shell two directories src and dist. In the src directory, let's create a .ts file in which we copy the following code:

main.ts

  function component() {
    const element = document.createElement('div');

      element.innerHTML = 'The app ran.';

    return element;
  }

  document.body.appendChild(component());

Add a .html file with the following code.

index.html

<!DOCTYPE html>

<html>
  <head>
    <meta charset="UTF-8">
    <title>KodFor</title>
  </head>

  <body>
      <h1>KodFor</h1>
    <h3>Webpack</h3>

    <my-app></my-app>

    <script src='app.bundle.js'></script>

  </body>
</html>

Let's execute the npm start command in the command shell

Output

My app
JavaScript

Categories