Gulp - Merge Two JSON file and create Angular Configuration file - angularjs

I am using gulp-ng-constant to create a config.json file for my angular project using below code:
*****UPDATED CODE*******
var gulp = require('gulp'),
uglify = require('gulp-uglify'),
ngConfig = require('gulp-ng-constant'),
baseDest = '../app',
extend = require("gulp-extend"),
pkg = require('./package.json');
gulp.task('config', function() {
gulp.src('./src/config.json')
.pipe(extend('./src/timezone.json')
.pipe(ngConfig({
name: pkg.name + '.config'
}))
.pipe(uglify())
.pipe(gulp.dest(baseDest + 'js/'))
.on('error', function(err) {
console.log(err);
});
});
// OUTPUT IS STILL SAME
and its work great and create a JSON file from me, something like,
angular.module("app.config",[]).constant("ID","XXXXXXXXXXXXXXXXXXXXXXXXXXX")}});
But now, i have more files to configure, except for config.json
So is there any way to first merge all the JSON files into one and then create a configuration file using gulp.
Thanks in adv.

You can merge JSONs via gulp. Look at the gulp-jsoncombine or gulp-extend.

Related

Gulp does not produce intended Css and Html folder

gulp build command in command prompt creates a folder js and also a file scripts.js in dist folder. But the same does not get created for Css and Html. My css and Html folder have atlest one file and are not empty.
const gulp = require('gulp');
const concat = require('gulp-concat');
const browserSync = require('browser-sync').create();
const scripts = require('./scripts');
const styles = require('./styles');
var devMode = false;
gulp.task('css',function(){
gulp.src(styles)
.pipe(concat('main.css'))
.pipe(gulp.dest('./dist/css'))
.pipe(browserSync.reload({
stream : true
}))
});
gulp.task('js',function(){
gulp.src(scripts)
.pipe(concat('scripts.js'))
.pipe(gulp.dest('./dist/js'))
.pipe(browserSync.reload({
stream : true
}))
});
gulp.task('html',function(){
gulp.src('./src/templates/**/*.html')
.pipe(gulp.dest('./dist/html'))
.pipe(browserSync.reload({
stream : true
}))
});
gulp.task('build',function(){
gulp.start(['css','js','html'])
});
gulp.task('browser-sync',function(){
browserSync.init(null,{
open : false,
server : {
baseDir : 'dist'
}
})
});
gulp.task('start',function(){
devMode = true;
gulp.start(['build','browser-sync']);
gulp.watch(['./src/css/**/*.css'],['css']);
gulp.watch(['./src/js/**/*.js'],['js']);
gulp.watch(['./src/templates/**/*.html'],['html']);
});
Following is the output
The project structure
I would suggest you use yeoman with a generator like Fountain so that you dont have to spend your time on building the gulp tasks . Fountain has a very good gulp setup which you could customize according to your need.
While loading the files with gulp.src you need to pass the path to the files , Here you have mentioned only gulp.src(require(./styles)) which I am not sure would work . Instead pass , gulp.src('**/*.css') which would scan through all the folders and take all the .css files.

how to config gulp file with gulp-useref for concatenate html file to js files?

i have project structure according below image:
and i have gulp file for building my projetc , below code is for uglify and minify my scripts :
gulp.task('useref', function(){
return gulp.src('*.html')
.pipe(useref())
.pipe(gulpIf('*.js', uglify()))
.pipe(gulpIf('*.css', cssnano()))
.pipe(gulp.dest('dist'))
});
now my question:
my project build successfully but no happening for my html file and concatenate it in to my scripts.min file , therefor when my project up h can't see any thing!!!!
] astonished what i do ?
gulp.task('useref', function(){
return gulp.src('script/**/*.html')
.pipe(useref())
.pipe(gulpIf('*.js', uglify()))
.pipe(gulpIf('*.css', cssnano()))
.pipe(gulp.dest('dist'))
});

Building Typescript for Angular using Gulp

I'm trying to setup an angularjs project according to Johnpapa's Angular Style Guide whilst using TypeScript and Gulp as a build tool. I believe Gulp is currently recommended over Grunt but I'm not very experienced with Gulp.
What I have:
My project currently looks like this:
src/
+- ts/ # contains .ts source files
+- typings/ # contains .d.ts typing definitions
+- html/ # contains .html files
dist/
+- bundle.js # single .js file containing compiled typescript and sourcemaps
Following the angular style guide I have created a separate .ts file for each angular element.
my-app.module.ts
----------------
angular.module('myApp', []);
for initialization of the module and another for a simple implementation of a controller:
my-controller.controller.ts
----------------------------
export class MyController {
testString = 'test';
}
angular
.module('myApp')
.controller('MyController', MyController);
typescript is configured using a simple tsconfig.json. (Note that filesGlob is not active yet - it will become available from TypeScript 2.0)
tsconfig.json
-------------
{
"exclude" : [
"node_modules"
],
"filesGlob" : [
"./src/typings/index.d.ts",
"./src/ts/**/*.ts",
"!./node_modules/**/*.ts"
],
"compilerOptions": {
"noImplicitAny": true,
"target": "es5",
"sourceMap" : true,
"outFile" : "./dist/bundle.js",
"removeComments": false
}
}
What I want:
I would ideally like to
Have Gulp monitor new or updated .ts files in ./src/ts/**/*.ts
Concatenate all the files from ./src/ts/**/*.ts. This is required for angular to work properly. Other methods I've tried using requirejs or browserify can't find the other .ts files without having to manually input references to these files.
Compile using the definitions from tsconfig.json. This would take into consideration the typings in ./src/typings/index.d.ts (for external modules including 'angular'). Also sourcemaps.
Possibly an uglify or babelify step to finish it.
What I tried:
I've tried following the manual from the typescriptlang handbook but this uses browserify and won't work with angular.
Gulp-typescript also has a note on concatenating files but the out option doesn't work like this:
var gulp = require('gulp');
var ts = require('gulp-typescript');
var tsProject = ts.createProject('tsconfig.json');
gulp.task('default', function () {
var tsResult = tsProject.src().pipe(ts(tsProject));
return tsResult.js.pipe(gulp.dest('dist'));
});
This configuration will output an empty file with only comments.
Another method mentioned in this question:
gulp.task('ts', function () {
gulp.src('./src/ts/**/*.ts')
.pipe(ts({
noImplicitAny: true,
out: 'output.js'
}))
.pipe(gulp.dest('./tmp/ts'));
});
gulp.task('default', ['ts'], function() {
gulp.src(['./tmp/ts/output.js'])
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(sourcemaps.write('/'))
.pipe(gulp.dest('./dist/'));
});
But this gave two issues: 1. Even though I only pointed at the .ts files in ./src/ts the typescript compiler started spewing errors from .ts in ./node_modules. 2. It still didn't manage to concatenate everything.
I'm at quite a loss here. Can anyone help me set up this build script? I'm surprised I couldn't find a similar working demo anywhere.
Solution:
I've configured the gulp environment based on the solution in this answer and removed the 'export' statement for classes / objects that are not inside a typescript module.
If that helps, here is a Angular Typescript Gulp Tutorial that has a basic TypeScript, Angular, Gulp, etc. setup that concatenate the app and the vendor/nodes files. There is the demo code on github.
/* File: gulpfile.js */
// grab our gulp packages
var gulp = require('gulp');
// Include plugins
var plugins = require("gulp-load-plugins")({
pattern: ['gulp-*', 'gulp.*', 'main-bower-files', 'del'],
replaceString: /\bgulp[\-.]/
});
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
// create a default task to build the app
gulp.task('default', ['jade', 'typescript', 'bowerjs', 'bowercss', 'appcss'], function() {
return plugins.util.log('App is built!')
});
In my example, we use Jade to HTML:
// Jade to HTML
gulp.task('jade', function() {
return gulp.src('src/**/*.jade')
.pipe(plugins.jade()) // pip to jade plugin
.pipe(gulp.dest('dist')) // tell gulp our output folder
.pipe(reload({stream: true}))
;
});
For TypeScript, we compiled into one single app.js file:
// TYPESCRIPT to JavaScript
gulp.task('typescript', function () {
return gulp.src('src/**/*.ts')
.pipe(plugins.typescript({
noImplicitAny: true,
out: 'app.js'
}))
.pipe(gulp.dest('dist/js/'))
.pipe(reload({stream: true}))
;
});
For bower, we merge all the js files in vendor.js and CSS in vendor.css:
// BOWER
gulp.task('bowerjs', function() {
gulp.src(plugins.mainBowerFiles())
.pipe(plugins.filter('**/*.js'))
.pipe(plugins.debug())
.pipe(plugins.concat('vendor.js'))
.pipe(plugins.uglify())
.pipe(gulp.dest('dist/js'));
});
gulp.task('bowercss', function() {
gulp.src(plugins.mainBowerFiles())
.pipe(plugins.filter('**/*.css'))
.pipe(plugins.debug())
.pipe(plugins.concat('vendor.css'))
.pipe(gulp.dest('dist/css'));
});
Custom CSS:
// APP css
gulp.task('appcss', function () {
return gulp.src('src/css/**/*.css')
.pipe(gulp.dest('dist/css/'))
.pipe(reload({
stream: true
}));
});
// CLEAN
gulp.task('clean', function(done) {
var delconfig = [].concat(
'dist',
'.tmp/js'
);
// force: clean files outside current directory
plugins.del(delconfig, {
force: true
}, done);
});
This is what reloads the browser when changes occur:
// Watch scss AND html files, doing different things with each.
gulp.task('serve', ['default'], function () {
// Serve files from the root of this project
browserSync.init({
server: {
baseDir: "./dist/"
}
});
gulp.watch("src/**/*.jade", ['jade']).on("change", reload);
gulp.watch("src/**/*.ts", ['typescript']).on("change", reload);
gulp.watch("src/**/*.css", ['appcss']).on("change", reload);
});
My tsconfig.json looks like this... I put the JS files that are automatically compiled from the text editor (Atom) into .tmp/js/atom ... some people put the .js in the same directory as the .ts but I find it confusing... less files is better for me:
{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"outDir": ".tmp/js/atom"
},
"exclude": [
"node_modules",
"typings"
]
}

gulp-ng-annotate - how to use it?

I want to minify my big angular project.
Using angular 1.5.0.
I'm trying to use the module gulp-ng-annotate to do so.
var gulp = require('gulp');
var ngAnnotate = require('gulp-ng-annotate');
gulp.task('default', function () {
return gulp.src('../www-myalcoholist-com-angular/model/app.js')
.pipe(ngAnnotate())
.pipe(gulp.dest('dist'));
});
when I execute this nodejs script, it fails silently. or... welll.. it doesn't do anything.
i gave it only the main app.js file as a parameter. can I some how give it the all project ?
when I run ng-annotate from terminal, it added annotations properly to my project.. well.. i hope :)
so why this script fails?
I'm new to gulp so any information would be greatly appreciated.
gulp-ng-annotate does not try to find other files in your application. You'll need to either concat your application into a single app.js file before piping to gulp-ng-annotate or src all files separately and pass them to`gulp-ng-annotate.
E.g. the concat method:
var gulp = require('gulp');
var ngAnnotate = require('gulp-ng-annotate');
var concat = require('gulp-concat');
gulp.task('default', function () {
return gulp.src('../www-myalcoholist-com-angular/model/**/*.js')
.pipe(concat('app.js'))
.pipe(ngAnnotate())
.pipe(gulp.dest('dist'));
});
A sample configuration -
gulp.task('app', function() {
return gulp.src([
// './bower_components/angular/angular.min.js',
// './bower_components/angular-sanitize/angular-sanitize.min.js',
//'./bower_components/angular-ui-select/dist/select.min.js',
// './bower_components/angular-ui-router/release/angular-ui-router.min.js',
'./components/**/*.js'])
.pipe(plumber())
.pipe(count('## js-files selected'))
.pipe(concat('./app/all.min.js', {newLine: ';'}))
.pipe(ngAnnotate({
// true helps add where #ngInject is not used. It infers.
// Doesn't work with resolve, so we must be explicit there
add: true
}))
.pipe(gulp.dest('./dist'));
});
This will produce a concatenated build js file. I have kept the vendor js files separate but you can have it any way you like.
P.S - Any other task e.g Linting is done separately in conjunction with watch task.

gulp-concat does not concat one of my files on heroku

I'm using gulp to generate a config.js file for angular, then use another gulp task to concat all .js files together, the gulp tasks look like this:
gulp.task('config', function() {
var environment = process.env.NODE_ENV || 'development';
gulp.src('public/config/' + environment + '.json')
.pipe(ngConstant({
name: 'app.config'
}))
.pipe(concat('public/js/config.js'))
.pipe(gulp.dest('.'));
});
gulp.task('js', ['config'], function() {
gulp.src('public/js/*.js')
.pipe(concat('app.js'))
.pipe(gulp.dest('public/dist'));
});
gulp.task('default', ['config', 'js']);
If I run gulp locally, everything works file.
But when I push to heroku, using this post install script:
"postinstall": "bower install && gulp"
I can see gulp run successfully, after adding some debug, I can see the config.js file is even created correctly, but the generated app.js does not include config.js. Can anyone suggest what might be wrong here?
UPDATE: I found it works if I do gulp config && gulp js but not gulp, is this because gulp is async and config.js wasn't created when js job started to run? but i thought I have already specified the task dependencies?
The problem is: I'm not returning a stream from tasks, for example the config task should be like this:
gulp.task('config', function() {
var environment = process.env.NODE_ENV || 'development';
var stream = gulp.src('public/config/' + environment + '.json')
.pipe(ngConstant({
name: 'app.config'
}))
.pipe(concat('public/js/config.js'))
.pipe(gulp.dest('.'));
return stream; // THIS IS IMPORTANT!
});

Resources