Add tsconfig.json properties to Gulp task - javascript

I keep on getting that error about using something different than ES5 standards while compiling, simply because I just started using TS and I don't know how to include the tsconfig.json directly in my Gulp task autocompile.
error TS1056: Accessors are only available when targeting ECMAScript 5 and higher
Is it possible to add my tsconfig.json file properties directly into my Gulp pipe?
Current gulpfile.js
'use strict';
var gulp = require('gulp');
var ts = require('gulp-typescript');
var tsProject = ts.createProject('tsconfig.json'); // TypeScript config
var merge = require('merge2'); // TypeScript requirement
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence');
gulp.task('sass', function () {
return gulp.src('app/assets/scss/**/*.scss')
.pipe(sass()) // Using gulp-sass
.pipe(gulp.dest('app/assets/css'))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task('typescript', function () {
var tsResult = gulp.src('app/assets/typescript/**/*.ts')
.pipe(ts({
declaration: true
}));
return merge([
tsResult.dts.pipe(gulp.dest('app/assets/definitions')),
tsResult.js.pipe(gulp.dest('app/assets/js'))
]);
});
gulp.task('watch', ['browserSync', 'sass'], function () {
gulp.watch('app/assets/typescript/**/*.ts', ['typescript']);
gulp.watch('app/assets/scss/**/*.scss', ['sass']);
// Reloads the browser whenever HTML or JS files change
gulp.watch('app/**/*.html', browserSync.reload);
gulp.watch('app/assets/js/**/*.js', browserSync.reload);
});
gulp.task('browserSync', function () {
browserSync.init({
server: {
baseDir: 'app'
},
});
});
gulp.task('useref', function () {
return gulp.src('app/*.html')
.pipe(useref())
.pipe(gulpIf('*.js', uglify()))
// Minifies only if it's a CSS file
.pipe(gulpIf('*.css', cssnano()))
.pipe(gulp.dest('dist'));
});
gulp.task('images', function () {
return gulp.src('app/assets/img/**/*.+(png|jpg|jpeg|gif|svg)')
// Caching images that ran through imagemin
.pipe(cache(imagemin({
interlaced: true
})))
.pipe(gulp.dest('dist/assets/img'));
});
gulp.task('fonts', function () {
return gulp.src('app/assets/fonts/**/*')
.pipe(gulp.dest('dist/assets/fonts'));
});
gulp.task('clean:dist', function () {
return del.sync('dist');
});
gulp.task('build', function (callback) {
runSequence('clean:dist', ['sass', 'useref', 'images', 'fonts'],
callback
);
});
gulp.task('default', function (callback) {
runSequence(['sass', 'typescript', 'browserSync', 'watch'],
callback
);
// Typescript compiler
});

I would recommend you to use your tsconfig.json as the only source of the properties. To do this change how you create tsResult:
var tsProject = ts.createProject('tsconfig.json');
var tsResult = tsProject.src().
.pipe(//....
Below is the complete task that works for me:
gulp.task('build.js.dev', () =>
{
var tsProject = ts.createProject('tsconfig.json');
var tsResult = tsProject.src()
.pipe(sourcemaps.init())
.pipe(tsProject());
return merge([
//Write definitions
//tsResult.dts.pipe(gulp.dest(TEMP_TARGET_FOLDER)),
//Write compiled js
tsResult.js.pipe(sourcemaps.write(
".",
{
includeContent: true,
sourceRoot: __dirname + "/dist"
})).pipe(gulp.dest(TEMP_TARGET_FOLDER))]);
});
The error you are getting is due to the fact that if you omit target compiler option the typescript compiler will fallback to ES3.

Related

Gulp livereload from build folder

Everything is working fine, except that LiveReload is not watching for changes, and therefore it does not auto-reload the page.
What am I doing wrong?
Here is my Gulp file:
// Gulp.js configuration
var
// modules
gulp = require('gulp'),
newer = require('gulp-newer'),
imagemin = require('gulp-imagemin'),
pug = require('gulp-pug'),
htmlclean = require('gulp-htmlclean'),
concat = require('gulp-concat'),
deporder = require('gulp-deporder'),
stripdebug = require('gulp-strip-debug'),
uglify = require('gulp-uglify'),
sass = require('gulp-sass'),
postcss = require('gulp-postcss'),
assets = require('postcss-assets'),
autoprefixer = require('autoprefixer'),
mqpacker = require('css-mqpacker'),
cssnano = require('cssnano'),
browserSync = require('browser-sync').create(),
// development mode?
devBuild = (process.env.NODE_ENV !== 'production'),
// folders
folder = {
src: 'src/',
build: 'build/'
};
// image processing
gulp.task('images', function () {
var out = folder.build + 'images/';
return gulp.src(folder.src + 'images/**/*')
.pipe(newer(out))
.pipe(imagemin({
optimizationLevel: 5
}))
.pipe(gulp.dest(out));
});
// Pug processing
gulp.task('pug', function buildHTML() {
var out = folder.build
return gulp.src(folder.src + 'views/*.pug')
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest(out))
});
// HTML processing
gulp.task('html', ['images'], function () {
var
out = folder.build + 'html/',
page = gulp.src(folder.src + 'html/**/*')
.pipe(newer(out));
// minify production code
if (!devBuild) {
page = page.pipe(htmlclean());
}
return page.pipe(gulp.dest(out));
});
// JavaScript processing
gulp.task('js', function () {
var jsbuild = gulp.src(folder.src + 'js/**/*')
.pipe(deporder())
.pipe(concat('main.js'));
if (!devBuild) {
jsbuild = jsbuild
.pipe(stripdebug())
.pipe(uglify());
}
return jsbuild.pipe(gulp.dest(folder.build + 'js/'));
});
// CSS processing
gulp.task('css', ['images'], function () {
var postCssOpts = [
assets({
loadPaths: ['images/']
}),
autoprefixer({
browsers: ['last 2 versions', '> 2%']
}),
mqpacker
];
if (!devBuild) {
postCssOpts.push(cssnano);
}
return gulp.src(folder.src + 'scss/styles.scss')
.pipe(sass({
outputStyle: 'nested',
imagePath: 'images/',
precision: 3,
errLogToConsole: true
}))
.pipe(postcss(postCssOpts))
.pipe(gulp.dest(folder.build + 'css/'));
});
gulp.task('browserSync', function () {
browserSync.init({
server: {
baseDir: folder.build
},
port: 3000
});
});
// run all tasks
gulp.task('run', ['pug', 'html', 'css', 'js']);
// watch for changes
gulp.task('watch', ['browserSync'], function () {
// image changes
gulp.watch(folder.src + 'images/**/*', ['images']);
// pug changes
gulp.watch(folder.src + 'views/**/*', ['pug'], browserSync.reload);
// html changes
gulp.watch(folder.src + 'html/**/*', ['html'], browserSync.reload);
// javascript changes
gulp.watch(folder.src + 'js/**/*', ['js'], browserSync.reload);
// css changes
gulp.watch(folder.src + 'scss/**/*', ['css'], browserSync.reload);
});
// default task
gulp.task('default', ['run', 'watch']);
A sample of our working watch gulp configuration is like:
var watch = require('gulp-watch');
watch('./src/**/*.html', function () {
browserSync.reload();
});

Gulp: How to concatenate files after they have compiled?

My goal is to compile and minify a few CSS and JS files, and one HTML file into a new HTML file which should have this kind of structure:
<script>
... compiled JS files ...
</script>
<style>
... minified CSS files ...
</style>
<html file>
This is my file structure:
This is my gulpfile:
const gulp = require('gulp');
const plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var csslint = require('gulp-csslint');
var cssComb = require('gulp-csscomb');
var cleanCss = require('gulp-clean-css');
var jshint = require('gulp-jshint'); // removed
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var minifyHtml = require('gulp-minify-html');
const babel = require('gulp-babel');
const inject = require('gulp-inject-string');
const gulpMerge = require('gulp-merge');
const del = require('del');
const runSequence = require('gulp-sequence');
gulp.task('clean', function () {
return del([
'dist/**/*',
]);
});
gulp.task('css', function () {
gulp.src(['src/**/*.css'])
.pipe(plumber())
.pipe(cssComb())
.pipe(csslint())
.pipe(csslint.formatter())
.pipe(concat('bundle.css'))
.pipe(gulp.dest('dist/'))
.pipe(rename({
suffix: '.min'
}))
.pipe(cleanCss())
.pipe(gulp.dest('dist/'))
});
gulp.task('js', function () {
gulp.src(['src/js/**/*.js'])
.pipe(concat('bundle.js'))
.pipe(babel({
presets: 'env'
}))
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(gulp.dest('dist/'))
.pipe(rename({
suffix: '.min'
}))
.pipe(uglify())
.pipe(gulp.dest('dist/'))
});
gulp.task('html', function () {
gulp.src(['src/html/**/*.html'])
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(rename({
suffix: '.min'
}))
.pipe(minifyHtml())
.pipe(gulp.dest('dist/'))
});
gulp.task('concatenateFiles', function() {
return gulpMerge(
gulp.src('dist/bundle.css')
.pipe(inject.wrap("\n<style>\n", "\n</style>\n")),
gulp.src('dist/bundle.js')
.pipe(inject.wrap("\n<script>\n", "\n</script>\n\n")),
gulp.src('src/html/player.html')
)
.pipe(concat('widget.html'))
.pipe(gulp.dest('dist/'));
});
gulp.task('concatenateFilesMinified', function() {
return gulpMerge(
gulp.src('dist/bundle.min.css')
.pipe(inject.wrap('<style>', '</style>')),
gulp.src('dist/bundle.min.js')
.pipe(inject.wrap('<script>', '</script>')),
gulp.src('dist/player.min.html')
)
.pipe(concat('widget.min.html'))
.pipe(gulp.dest('dist/'));
});
const js = 'src/**/*.js';
const css = 'src/**/*.css';
const html = 'src/**/*.html';
const all = [js, css, html];
gulp.task('default', ['clean', 'js', 'css', 'html'], function () {
gulp.watch(js, ['js']);
gulp.watch(css, ['css']);
gulp.watch(html, ['html']);
setTimeout(function() {
runSequence(['concatenateFiles', 'concatenateFilesMinified']);
}, 2000);
});
I know this is a bad approach, especially if you look at the setTimeout(), but I'm just so lost at this point (and this is my first gulpfile).
I've also tried this:
gulp.task('default', ['clean', 'js', 'css', 'html', 'concatenateFiles', 'concatenateFilesMinified'], function () {
gulp.watch(js, ['js']);
gulp.watch(css, ['css']);
gulp.watch(html, ['html']);
});
But the problem is that all dependency tasks are executed in parallel, so the 'concatenateFiles' and 'concatenateFilesMinified' are started before their dependencies (eg JS, CSS and HTML) are ready.
Furthermore, gulp.watch() would only work for js, css and html tasks.
How do I do this properly?
TLDR:
I want to:
build CSS, JS and HTML files from src folder (1 file for each type)
concatenate those three files into one file (wrapping JS into <script>, CSS into <style>) into dist/widget.html
minify the file from step 2. into dist/widget.min.html
I want these 3 things to happen when I run gulp default.
Furthermore, I also want files from step 2. and 3. to be refreshed every time I make changes to files in src/ folder
runSequence should work with tasks, which are returning something. Add 'return' for js, html, concatenateFiles, concatenateFilesMinified

Error in gulp while copying files

My command line shows following error while i entered the gulp watch command. Since gulp is searching css files from inside the app directory instead of searching it from bower_components.I have tried using minify-css as well as copy-css.Both are not working.
events.js:160
throw er; // Unhandled 'error' event
^
Error: Path F:\Backup Folder\coursera-project\Full stack course\Angular Js\Assignments\week1\confusion\app\bower_components\bootstrap\dist\css\bootstrap.min.css not found!
My gulpfile.js file
'use strict';
var gulp = require('gulp'),
cleancss = require('gulp-clean-css'),
jshint = require('gulp-jshint'),
stylish = require('jshint-stylish'),
uglify = require('gulp-uglify'),
usemin = require('gulp-usemin'),
imagemin = require('gulp-imagemin'),
rename = require('gulp-rename'),
concat = require('gulp-concat'),
notify = require('gulp-notify'),
cache = require('gulp-cache'),
changed = require('gulp-changed'),
rev = require('gulp-rev'),
browserSync = require('browser-sync'),
del = require('del'),
ngannotate = require('gulp-ng-annotate');
gulp.task('jshint', function() {
return gulp.src('app/scripts/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter(stylish));
});
// Clean
gulp.task('clean', function() {
return del(['dist']);
});
// Default task
gulp.task('default', ['clean'], function() {
gulp.start('usemin', 'imagemin','copyfonts');
});
gulp.task('usemin',['jshint'], function () {
return gulp.src('./app/**/*.html')
.pipe(usemin({
css:[cleancss(),rev()],
js: [ngannotate(),uglify(),rev()]
}))
.pipe(gulp.dest('dist/'))
});
// Images
gulp.task('imagemin', function() {
return del(['dist/images']), gulp.src('app/images/**/*')
.pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
.pipe(gulp.dest('dist/images'))
.pipe(notify({ message: 'Images task complete' }));
});
gulp.task('copyfonts', ['clean'], function() {
gulp.src('./bower_components/font-awesome/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
gulp.src('./bower_components/bootstrap/dist/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
});
// Watch
gulp.task('watch', ['browser-sync'], function() {
// Watch .js files
gulp.watch('{app/scripts/**/*.js,app/styles/**/*.css,app/**/*.html}', ['usemin']);
// Watch image files
gulp.watch('app/images/**/*', ['imagemin']);
});
gulp.task('browser-sync', ['default'], function () {
var files = [
'app/**/*.html',
'app/styles/**/*.css',
'app/images/**/*.png',
'app/scripts/**/*.js',
'dist/**/*'
];
browserSync.init(files, {
server: {
baseDir: "dist",
index: "index.html"
}
});
// Watch any files in dist/, reload on change
gulp.watch(['dist/**']).on('change', browserSync.reload);
});
I am also not able to copy html files to my dist folder.

Gulp file not compiling less file to css

I have a gulp file, and when I run it only the JavaScript files get complied and the less files doesn't get compiled, and I cannot seem to understand why is this happening.
This is my gulp file:
'use strict';
var path = require('path');
var gulp = require('gulp');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var less = require('gulp-less');
var watch = require('gulp-watch');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var livereload = require('gulp-livereload');
var jsFiles = ['*.js', 'src/**/*.js'];
// js hints
gulp.task('hints', function(){
return gulp.src(jsFiles)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish', {
verbose: true
}))
.pipe(jscs()); });
// less
gulp.task('less', function () {
return gulp.src('./public/src/less/main.less')
.pipe(less({ paths: [path.join(__dirname, 'less', 'includes')] }))
.pipe(gulp.dest('./public/src/less/css')); });
// concat
gulp.task('concat', ['concat:css', 'concat:js']); gulp.task('concat:css', function() {
return gulp.src([
'public/lib/bower_components/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bower_components/swiper/dist/css/swiper.min.css',
'public/lib/bower_components/font-awesome/css/font-awesome.min.css',
'public/src/less/css/main.css'
])
.pipe(concat('styles.css'))
.pipe(gulp.dest('./public/build/')); }); gulp.task('concat:js', function() {
return gulp.src([
'public/lib/bower_components/jquery/dist/jquery.min.js',
'public/lib/bower_components/bootstrap/dist/js/bootstrap.min.js',
'public/lib/bower_components/swiper/dist/js/swiper.min.js',
'public/lib/bower_components/jquery.scrollTo/jquery.scrollTo.min.js',
'public/lib/bower_components/jquery.localScroll/jquery.localScroll.min.js',
'public/lib/bower_components/jquery-waypoints/lib/jquery.waypoints.min.js',
'public/lib/bower_components/gsap/src/uncompressed/TweenMax.js',
'public/lib/bower_components/scrollmagic/scrollmagic/uncompressed/ScrollMagic.js',
'public/lib/bower_components/scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap.js',
'public/lib/bower_components/scrollmagic/scrollmagic/uncompressed/plugins/debug.addIndicators.js',
'public/src/js/init.js',
'public/src/js/utils.js',
'public/src/js/main.js'
])
.pipe(concat('scripts.js'))
.pipe(gulp.dest('./public/build/')); });
// watch
gulp.task('watch', ['watch:css', 'watch:js']);
gulp.task('watch:css', function () {
gulp.watch('public/src/less/*.less', ['less', 'concat:css']);
});
gulp.task('watch:js', function () {
gulp.watch('public/src/js/*.js', ['concat:js', 'hints']);
});
gulp.task('build', [ 'less', 'concat']);
gulp.task('development', [ 'less', 'concat', 'watch']);
When I run gulp development the css and js file gets created under the build folder but because the less files dont get compiled to css the css file under build folder has none of my styles.
Does someone know how to solve this issue?
Thank you

Getting gulp task to build two css files

I have a project using gulp to compile all my scss. Now I have a need for two separate builds. Currently my task builds out sites-bootstrap.css. I have another set of css files that is set up to build sites-life-bootstrap.css that will have minimal components in it. I just can't seem to get gulp to build that separate css file.
Below is my current working gulp file.js.
/* jshint node:true */
'use strict';
// generated on 2015-02-10 using generator-gulp-webapp 0.2.0
var gulp = require('gulp');
var fs = require('fs');
require('gulp-grunt')(gulp);
var runs = require('run-sequence');
var $ = require('gulp-load-plugins')();
//build the compile using assemble + grunt
//Note: Assemble's gulp task is very alpha - easier to do this
gulp.task('compile', function(){
gulp.run('grunt-compile');
});
gulp.task('styles', function () {
var sassPaths = ['./bower_components/bootstrap-sass-official/assets/stylesheets'];
return gulp.src('app/styles/sites-bootstrap.scss')
.pipe($.plumber())
.pipe($.sass({
style: 'expanded',
includePaths: sassPaths,
precision: 10
}))
.pipe($.autoprefixer({browsers: ['last 1 version']}))
.pipe($.replace('../bower_components/bootstrap-sass-official/assets/fonts/bootstrap','../fonts'))
.pipe(gulp.dest('dist/styles'));
});
gulp.task('jshint', function () {
return gulp.src('app/scripts/**/*.js')
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.jshint.reporter('fail'));
});
gulp.task('html', ['styles'], function () {
var lazypipe = require('lazypipe');
var cssChannel = lazypipe()
.pipe($.csso);
var assets = $.useref.assets({searchPath: '{.tmp,app}'});
//all the build instructions are in build.html NOT in the hbs files
return gulp.src('app/useref/build.html')
.pipe(assets)
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.css', cssChannel()))
.pipe(assets.restore()) //do the asset replacement in the html files
.pipe($.useref())
.pipe(gulp.dest('dist'));
});
gulp.task('images', function () {
return gulp.src('app/images/**/*')
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('dist/images'));
});
gulp.task('fonts', function () {
return gulp.src(require('main-bower-files')().concat('app/fonts/**/*'))
.pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
.pipe($.flatten())
.pipe(gulp.dest('dist/fonts'));
});
gulp.task('extras', function () {
return gulp.src([
'app/extras/*.*'
], {
dot: true
})
.pipe(gulp.dest('dist'));
});
/**
* clean out dist and .tmp
*/
gulp.task('clean', function (cb) {
var del = require('del');
del([
'./.tmp',
'./dist/*',
], cb);
});
gulp.task('connect', ['styles'], function () {
var serveStatic = require('serve-static');
var serveIndex = require('serve-index');
var app = require('connect')()
.use(require('connect-livereload')({port: 35729}))
.use(serveStatic('dist'))
.use(serveIndex('dist'));
require('http').createServer(app)
.listen(9000)
.on('listening', function () {
console.log('Started connect web server on http://localhost:9000');
});
});
gulp.task('cdn', function(){
var json = fs.readFileSync('gulp-aws.json');
var aws = JSON.parse(json);
var opts = aws.cdn;
// create a new publisher
var publisher = $.awspublish.create(opts);
var sourceFolder = ['./dist/styles','./dist/fonts','./dist/images'];
return gulp.src(sourceFolder)
// gulp-awspublish-router defines caching and other options (see above)
//.pipe(awspublishRouter(awsPubRouterOpts))
// publisher will add Content-Length, Content-Type and headers specified above
// if not specified it will set x-amz-acl to public-read by default
// i think the parallelization was causing it to miss some files
.pipe(publisher.publish())
// .pipe(publisher.publish(null, { force: true }))
// delete stuff that has been deleted locally
// can't do this because it will kill 1.9
//.pipe(publisher.sync())
// create a cache file to speed up consecutive uploads
.pipe(publisher.cache())
// print upload updates to console
.pipe($.awspublish.reporter());
});
gulp.task('serve', function (done) {
runs( ['build'], ['watch'], ['open'], done);
});
gulp.task('open', function(){
require('opn')('http://localhost:9000');
});
gulp.task('watch', ['connect'], function () {
$.livereload.listen();
// watch for changes
gulp.watch([
'dist/**/*.html',
'.tmp/styles/**/*.css',
'dist/scripts/**/*.js',
'dist/images/**/*'
]).on('change', $.livereload.changed);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/**/*.hbs', ['compile']);
});
gulp.task('reload', function(){
$.livereload.changed();
});
gulp.task('deploy', function(done) {
// return gulp.src('./dist/**/*')
// .pipe($.ghPages({origin: 'upstream'}));
console.error('DEPRECATED: Deployment to gh-pages is now handled by Travis CI.');
done();
});
gulp.task('build-report', function () {
return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});
gulp.task('build', function (done) {
runs( ['clean'], ['jshint', 'html', 'images', 'fonts', 'extras'], 'compile', 'build-report', done);
});
gulp.task('default', ['clean'], function () {
gulp.start('build');
});
Here was one attempt at just adding multiple outputs to the styles task:
gulp.task('styles', function () {
var sassPaths = ['./bower_components/bootstrap-sass-official/assets/stylesheets'];
return gulp.src('app/styles/sites-bootstrap.scss', 'app/styles/sites-lite-bootstrap.scss')
.pipe($.plumber())
.pipe($.sass({
style: 'expanded',
includePaths: sassPaths,
precision: 10
}))
.pipe($.autoprefixer({browsers: ['last 1 version']}))
.pipe($.replace('../bower_components/bootstrap-sass-official/assets/fonts/bootstrap','../fonts'))
.pipe(gulp.dest('dist/styles'));
});

Categories

Resources