Freitag, 13. Juli 2018

Building a library from javascrpt and typescript with gulp using require

When building typescript with tsc you usually end up in a folder structure representing the structure of the source files. If all of the code needs to go in one library, the folder structure will be lost and this must be reflected in the require dependencies. I have a lot of older javascript code that I want to combine with new typescript code into one library.

I ended up with a solution, that allows me to build the code with tsc for review only into a file structure and gulp packing everything together in a single lib.

The tsconfig.json: nothing special except for that I needed to set the moduleResolution to "Node" so tsc finds the type definitions that I installed by npm.
{
"compilerOptions": {
"target": "es5",
"module": "AMD",
"outDir":"./src/built",
"sourceMap": true,
"moduleResolution": "Node",
"typeRoots":[
"node_modules/@types"
]
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}


One thing getting used to is, that tsc creates all typescript code with relative dependencies from the file that starts the whole dependency tree, usually the file index.ts. So wherever this file is, all files that are imported there have relative dependecies to that file. So putting it into a folder one or more levels higher than the other files creates a nice naming structure.

In the gulpfile.js this will create the source from the typescript code
var buildTs = function () {
const ts = require("gulp-typescript");
const tsProject = ts.createProject('tsconfig.json', { outFile: "uiTs.js" } );

return gulp
.src('src/**/*.ts')
.pipe(tsProject());
}

Another thing special: I do not use  tsProject.src()  because actually I build more than one library and set the folder by using  gulp.src()   instead.

The final task
gulp.task('build', function () {
return merge(
gulp.src(srcUi),
buildTs(),
getTemplates()
)

// common preparation
.pipe(concat('mylib.js'))
.pipe(injectVersion())
.pipe(banner(comment, { pkg: pkg }))
// source file
.pipe(gulp.dest(pkg.config.paths.dist))
// source maps
.pipe(sourcemaps.init())
.pipe(sourcemaps.identityMap())
.pipe(uglify(uglifyOptions))
.pipe(rename('mylib.min.js'))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(pkg.config.paths.dist))
});


Whenever I want to check the code created I do "tsc", whenever I build the full thing I go "gulp build".


Keine Kommentare:

Kommentar veröffentlichen