Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 742
Mark Cooper Avatar asked Dec 12 '17 13:12

Mark Cooper


People also ask

What bundle would you use to minify CSS and/or JavaScript on a production environment?

Click on wwwroot folder, select the css file you want minified, then right click and choose bundler & minifier. Then from popup minify file. It will be the same file name with the minified version.

How do you minify TypeScript?

The TypeScript compiler does not support the generation of minifies or obfuscated code. you will need to use another tool against the JavaScript output of the compiler. You can use YUI Compressor, JSMin or Closure Compiler to minify JS code.

How do you minify a file in JavaScript?

To minify JavaScript, try UglifyJS. The Closure Compiler is also very effective. You can create a build process that uses these tools to minify and rename the development files and save them to a production directory.


1 Answers

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>
like image 102
Chui Tey Avatar answered Nov 15 '22 10:11

Chui Tey