Search code examples
typescriptvisual-studio-2017bundling-and-minificationsource-mapsweb-essentials

Compile, bundle and minify typescript into JavaScript using VS2017


I have a group of typescript files in my solution and I am compiling these to JS using typescript features directly within Visual Studio 2017. I am using tsconfig.json file.

I am able to bundle the output JS files in either VS or tsconfig.

I am able to use WebEssentials to minify and map *bundle.js.min back to *.bundle.js

What is the correct sequence for compiling, bundling, minifying and mapping within VS2017?

- project.csproj
  - scripts //output files
    - my.bundle.js
    - my.bundle.min.js
    - my.bundle.min.js.map
  - src //input files
    - mytypes.ts
    - mylogic.ts
    - mybaselogic.ts

(NOTE: I don't want to add the burden of WebPack, Babel or Grunt to my solution)


Solution

  • The good news is you can get very far with the limited toolset of Typescript and Web Essentials.

    The key step is to create a tsconfig.json in your src directory:

    {
      "compilerOptions": {
        /* Basic Options */
        "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
        "module": "amd",                          /* Specify module code generation: */
        "sourceMap": true,                        /* Generates corresponding '.map' file. */
        "outFile": "../scripts/bundle.js",   
      }
    }
    

    and add a NuGet package to Typescript. This will alter your project automatically to automatically recreate bundle.js on each build.

    You are now able to import the bundled javascript files using an AMD loader like almond.js:

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/almond.min.js"></script>
    <script src="scripts/bundle.min.js"></script>
    <script>
        // assuming your program logic is here
        require('mylogic');
    </script>