I can successfully compile my TypeScript project into a single JS file with source maps using something like this:
tsc --sourcemap --out app.js app.ts
I can also successfully minify that output using UglifyJS, while keeping source maps intact:
uglifyjs app.js --source-map app.js.map --in-source-map app.js.map -o app.js
However, I would like to go slightly further. I want to combine my compiled TypeScript code (app.js
) with a couple third-party JS libraries into a single minified file that maintains source maps pointing back to the original TypeScript (for my code) or JavaScript (for the third-party libraries).
I tried something like this, basically just adding a JS library file to the input to UglifyJS:
uglifyjs app.js lib/javascript-library.js --source-map app.js.map --in-source-map app.js.map -o app.js
Unfortunately, that doesn't seem to work. It does successfully combine everything into one file, and the source maps for the TypeScript code seem to be preserved. But when I put an error in lib/javascript-library.js
, the JS console in my browser (using source maps) says the error is in one of my TypeScript files, which is obviously wrong.
I am a TypeScript newb and I can't imagine I'm the first one to want to combine TS output with random JS libraries in a single minified file with source maps, but I can't find anyone talking about it. So maybe my approach is just completely wrong?
Typescript compiler isn't so smart, to do this you need use more specific tools. Example: gulpjs.
Requirements (if you know gulpjs skip this):
npm install -g typescript gulp
to install gulp taskrunnernpm init
and follow instruction to create package.jsonnpm install gulp gulp-typescript gulp-concat gulp-uglify gulp-sourcemaps --save-dev
to install ts compile, concat, uglify e generate sourcemaps toolsDefine 'compile' task in gulpfile.js :
var gulp = require('gulp');
var ts = require('gulp-typescript');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
gulp.task('compile', function() {
var tsResult = gulp.src('app.ts')
.pipe(sourcemaps.init()) // This means sourcemaps will be generated
.pipe(ts({
sortOutput: true,
// ...
}));
return tsResult
.pipe(concat('lib/js-library.js')) // You can use other plugins that also support gulp-sourcemaps
.pipe(uglify())
.pipe(sourcemaps.write()) // Now the sourcemaps are added to the .js file
.pipe(gulp.dest('release/'));
});
And now, run gulp compile
and see the magic!
Learn this packages and build your custom task compile.