I have my Angular app in which my index.html lists all my services and controllers JS files.
e.g. A lot of these lines <script src="services/loginService.js"></script>
For going into production I'd like to simplify this and just reference one js file (which is a minified version).
What tools have people found useful for doing this?
I'm guessing gulp?
Any advice would be appreciated.
Thanks.
In gulp, you can do it as follows:
Here is a sample gulpfile I have set up locally. You can use the scripts task or the useref task. Useref allows you to specify which files should be minified.
// Include gulp
var gulp = require('gulp');
// Include Our Plugins
var jshint = require('gulp-jshint');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var rename = require('gulp-rename');
var babel = require('gulp-babel');
var webserver = require('gulp-webserver');
var connect = require('gulp-connect');
var gulpIgnore = require('gulp-ignore');
var useref = require('gulp-useref');
var minifyCSS = require('gulp-minify-css');
var autoprefixer = require('gulp-autoprefixer');
var rename = require('gulp-rename');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var outputDir = 'dist';
var jsLintIgnore = 'app/js/bootstrap-3.3.6/**/*.js';
// run a local webserver from app directory
gulp.task('webserver', function() {
gulp.src('app')
.pipe(webserver({
livereload: true,
fallback: './src/index.html',
//port: 8000, // Default is 8000
//directoryListing: true,
open: true
}));
});
// Lint Task - checks any JavaScript file in our js/ directory and makes sure there are no errors in our code.
gulp.task('lint', function() {
return gulp.src('app/js/**/*.js')
.pipe(jshint())
//.pipe(gulpIgnore.include(jsLintIgnore))
.pipe(jshint.reporter('default'));
});
gulp.task('useref', function(){
return gulp.src('app/*.html')
.pipe(useref())
// Minifies only if it's a JavaScript file
.pipe(gulpIf('js/**/*.js', uglify()))
.pipe(gulpIf('css/**/*.css', cssnano()))
.pipe(gulp.dest('dist'))
});
// Compile Our Sass - compiles any of our Sass files in our scss/ directory into CSS and saves the compiled CSS file in our dist/css directory.
gulp.task('sass', function() {
return gulp.src('app/scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('app/css'));
});
gulp.task('css', function(){
gulp.src('app/css/**/*.css')
.pipe(minifyCSS())
.pipe(rename('style.min.css'))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9'))
.pipe(gulp.dest('dist/css'))
});
gulp.task('images', function(){
return gulp.src('app/images/**/*.+(png|jpg|gif|svg)')
.pipe(imagemin())
.pipe(gulp.dest('dist/images'))
});
// Concatenate & Minify JS - concatenates all JavaScript files in our js/ directory and saves the ouput to our dist/js directory. Then gulp takes
// that concatenated file, minifies it, renames it and saves it to the dist/js directory alongside the concatenated file.
gulp.task('scripts', function() {
return gulp.src('app/js/**/*.js')
.pipe(concat('all.js'))
.pipe(gulp.dest('dist'))
.pipe(rename('all.min.js'))
.pipe(uglify())
.pipe(gulp.dest('dist/js'));
});
// Watch Files For Changes - run tasks as we make changes to our files.
gulp.task('watch', function() {
gulp.watch('app/js/**/*.js', ['lint', 'scripts']);
gulp.watch('app/scss/**/*.scss', ['sass']);
});
// Default Task - used as a grouped reference to our other tasks. This will be the task that is ran upon entering gulp into the command line without any additional parameters.
gulp.task('default', ['webserver', 'lint', 'sass', 'useref','images', 'watch']);
In your html you would wrap the js files you wanted minifed with the following:
<!--build:js js/main.min.js -->
<script src="/js/script1.js"></script>
<script src="/js/script2.js"></script>
<script src="/js/script3.js"></script>
<!-- endbuild -->
This would create a minified file called: js/main.min.js in your dist folder. As you can see I'm doing the same with my css files. You can wrap them in tags as well to target certain or all css files:
<!--build:css css/styles.min.css-->
<link rel="stylesheet" href="/css/styles1.css">
<link rel="stylesheet" href="/css/styles2.css">
<link rel="stylesheet" href="/css/styles3.css">
<!--endbuild-->
This gulp file assumes the following directory structure, but you can change it to suit your environment:
- Root Folder
- /app (development environment)
- /css
- /images
- /js
- /scss
- index.html
- /dist (production version of site here)
- /css
- /images
- /js
- index.html
- /node_modules
- bower.json
- gulpfile.js
- package.json
Here is a great YouTube series on getting started with gulp.
https://www.youtube.com/watch?v=dwSLFai8ovQ
Now having said all that, I prefer webpack. It has a bit of a steeper learning curve though so Gulp may be a good place to start.
Related
I'm using Gulp to compile my type script into java script. When I initiate the Gulp command it will compile everything in my src folder and puts the compiles files in dist folder which are is Java script now but i only see only one file present in dist folder after compilation i.e. config.json where i am expecting all the files in src to be present in dist after compilation. I am using gulp compile command to compile my files in SRC.
Kindly scroll down the code below to see the folder structure as well.
Thank you.
Here's my gulpfile.js
var gulp = require('gulp');
var ts = require('gulp-typescript');
var zip = require('gulp-zip');
var del = require('del');
var install = require('gulp-install');
var runSequence = require('run-sequence');
var awsLambda = require("node-aws-lambda");
var sourcemaps = require('gulp-sourcemaps');
var gulpMocha = require('gulp-mocha');
var gutil = require('gulp-util');
const babel = require('gulp-babel');
gulp.task('clean', function () {
return del(['./dist','./testJs', './dist.zip']);
});
gulp.task('compile', function () {
return gulp.src(['src/**/*.ts' ]) //'typings/**/*.d.ts'])
.pipe(sourcemaps.init())
.pipe(ts({
noImplicitAny: false,
removeComments: true,
preserveConstEnums: true,
target: 'es2015',
module: 'commonjs',
noExternalResolve: true,
exclude: ["node_modules", "dist"]
}))
.pipe(babel({
presets: [ 'es2015' ],
plugins: ['transform-runtime']
}))
// sourceRoot must be relative to the running directory
// It appears VSCode does resolve the path relative to the cwd
// so using something like /src doesn't work, it has to be relative
// to the /dist folder where we will run the app from
// Need to test if maps help when errors are thrown in aws and if we should upload them
.pipe(sourcemaps.write('.', { sourceRoot: '../src' }))
.pipe(gulp.dest('./dist'))
,
gulp.src(['src/**/*.json'])
.pipe(gulp.dest('./dist'));
});
gulp.task('deploy', function (callback) {
return runSequence(
'clean',
'compile',
'compiletest',
'test',
'node-mods',
callback
);
});```
**Folder structure before running gulp compile**
|
|_ [src folder]
|_CC_ToMRDR
|_Central Repository
app.ts
config.json
test.ts
|_ [other folder's and files like node modules,package.json,tsconfig.json etc]
**Folder structure after running gulp compile**
|
|_ [src folder]
|_CC_ToMRDR
|_Central Repository
app.ts
config.json
test.ts
|
|_ [dist folder]
config.json
|_ [other folder's and files like node modules,package.json,tsconfig.json etc]
Try changing the first gulp.src like this:
return gulp.src('src/**/*.ts')
and the second
.pipe(gulp.src('src/**/*.json'))
Comma breaks the compilation. The second gulp.src must be added as a pipe or it overwrites the first (cfr. https://gulpjs.com/docs/en/getting-started/working-with-files/).
More in depth:
gulp.task('compile', function() {
return gulp.src('src/**/*.ts')
// some coding here
.pipe(gulp.dest('./dist'))
.pipe(gulp.src('src/**/*.json'))
.pipe(gulp.dest('./dist'));
});
Sorry for the edits, but you’re using an older Gulp.js syntax and I was a bit confused.
Link to Github Repo: https://github.com/janschloss/boilerplate
My problem is that only scss changes get recognized by BrowserSync in Gulp (no html or js or /img changes). I guess that is because scss changes are streamed directly. Weirdly I had one build which recognized html and img changes though I can't find that again.
Does someone see the mistake?
"use strict";
// Define packages
var gulp = require('gulp'),
sass = require('gulp-sass'),
clean = require('gulp-clean'),
sourcemaps = require('gulp-sourcemaps'),
autoprefixer = require('gulp-autoprefixer'),
plumber = require('gulp-plumber'),
imagemin = require('gulp-imagemin'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
strip = require('gulp-strip-comments'),
browserSync = require('browser-sync');
// Define file paths
var scssSrc = 'src/scss/**/*.scss',
jsSrc = 'src/js/*.js',
htmlSrc = 'src/*.html',
imgSrc = 'src/img/*';
// BrowserSync config
gulp.task('browserSyncInit', function() {
browserSync.init({
server: {
baseDir: 'dist'
}
});
gulp.watch('./dist/*').on('change', browserSync.reload);
});
// Concat scss files, compile compressed to css, prefix css, strip comments and create sourcemap
gulp.task('sass', function() {
return gulp.src(scssSrc)
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(concat('main.min.scss'))
.pipe(sass({outputStyle: 'compressed'}))
.pipe(autoprefixer())
.pipe(strip.text())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/css'))
.pipe(browserSync.reload({
stream: true
}));
});
// Concatenate, uglify, strip comments and create sourcemap for js files
gulp.task('js', function() {
return gulp.src(jsSrc)
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(concat('main.min.js'))
.pipe(uglify())
.pipe(strip())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/js'));
});
// Image optimization
gulp.task('img', function () {
return gulp.src(imgSrc)
.pipe(imagemin({
progressive: true
}))
.pipe(gulp.dest('dist/img'));
});
// Clean task
gulp.task('clean', function() {
return gulp.src('dist')
.pipe(clean());
});
// Copy html
gulp.task('copy', function() {
return gulp.src(htmlSrc)
.pipe(gulp.dest('dist/'));
});
// Default Task
gulp.task('default', ['clean', 'copy', 'sass', 'js', 'img', 'browserSyncInit'], function () { //todo asynchronous
gulp.watch(scssSrc, ['sass']);
gulp.watch(jsSrc, ['js']);
gulp.watch(imgSrc, ['img']);
gulp.watch(htmlSrc, ['copy']);
});
I think
gulp.watch('./dist/*').on('change', browserSync.reload);
is the relevant line. Is there anything wrong with my path?
My relevant folder structure looks like:
gulpfile.js
src
dist
Changes are made in src and copied over to dist on runtime with gulp.
Thanks!
I can't explain it. But when I remove your watch call from the browserSyncInit task and put it in the callback for the default task along side the other watches, everything works fine.
Relevant pieces of code:
// BrowserSync config
gulp.task('browserSyncInit', function() {
browserSync.init({
server: {
baseDir: 'dist'
}
});
});
// Default Task
gulp.task('default', ['clean', 'copy', 'sass', 'js', 'img', 'browserSyncInit'], function () { //todo asynchronous
gulp.watch(scssSrc, ['sass']);
gulp.watch(jsSrc, ['js']);
gulp.watch(imgSrc, ['img']);
gulp.watch(htmlSrc, ['copy']);
gulp.watch('./dist/**/*').on('change', function () {
console.log("Watch hit");
browserSync.reload();
});
});
Is this ideal at all for your gulp file? I can kind of understand the thinking of having the watch originally triggered inside the other task.
Very weird thing I noticed; Sometimes the DIST watch would take and all the other watches wouldn't. As if there is a race condition happening on which ones get registered and the others get overwritten. When they were separated like you had them originally, either SRC watches worked or DIST watches worked. I could edit files in DIST directly when the DIST watch was working and trigger reload.
Keeping all the watches together in that CB function works for me using your github project.
I also noticed another unrelated issue. Rerunning your gulp file required me to rm -rf dist first other wise I got errors.
I think the problem is with the glob: './dist/*' - it will only watch the contents of dist. I think you want './dist/**/*' to watch the folder and all subfolders.
After changing my project to be organized into src/ and dist/ folders, my changes aren't being compiled and my browsersync task is no longer reloading the page. If I change the color of a div for instance, the color is not updated even if I stop and restart the gulp task. So my question is, how do I change my gulp tasks to watch for changes in the new file structure I am using, and how do I trigger the reload task once the watch task recognizes a change to a file? I think the reload task works, on a previous working version of this gulpfile gulp.watch was working so it doesn't appear to be a problem with that. I tried changing gulp.watch to browserSync.watch as per this answer but that didn't fix it.
I'm guessing this is a problem with my watch task or the browsersync.init but I'm totally stumped.
To be clear, I am making a static webpage using Jade, Bourbon Neat, SCSS, Gulp, and Browsersync.
Here's a link to the full GitHub repo for this project if that helps!
This is my current file structure:
/
dist/
css/
js/
index.html
node_modules/
src/
jade/
js/
scss/
.gitignore
gulpfile.js
package.json
And this is my gulpfile.js:
// VARIABLES
var gulp = require('gulp');
var jade = require('gulp-jade');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var cssmin = require('gulp-cssmin');
var neat = require('node-neat').includePaths;
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
// TASKS
// Jade task
gulp.task('jade', function() {
return gulp.src('src/jade/**/*.jade')
.pipe(jade({ pretty: true }))
.pipe(gulp.dest('dist/'))
});
// SCSS task
gulp.task('scss', function() {
return gulp.src('src/scss/**/*.scss')
.pipe(sass({ style: 'compressed',
noCache: true,
includePaths: neat }))
.pipe(autoprefixer())
.pipe(cssmin())
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('dist/css'))
});
// JS task
gulp.task('js', function() {
return gulp.src('src/js/**/*.js')
.pipe(uglify())
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('dist/js/'))
});
// Watch files for changes
gulp.task('watch', ['browser-sync'], function() {
gulp.watch('dist/**/*.html', reload);
gulp.watch('src/scss/**/*.scss', ['scss', reload]);
gulp.watch('src/**/*.jade', ['jade']);
gulp.watch('src/**/*.js', ['js']);
});
// Start Browsersync server
gulp.task('browser-sync', function() {
browserSync.init(['dist/css/**/*.css', 'dist/js/**/*.js'], {
server: {
baseDir: "dist/"
}
});
});
// Default task
gulp.task('default', ['scss', 'jade', 'js', 'watch', 'browser-sync']);
I have pulled your repo and made some fixes, will push under the "fixes" branch. Few things:
Your index.html was referencing your unminified css, while you only exporting minified.
the watch list needed the subfolders prefxied, so gulp.watch('src/js/**/*.js', ['js']); and not gulp.watch('src/**/*.js', ['js']);
Your browserSync.init was referencing the wrong directories (src and not dist).
What worked for me was to switch gulp.watch to browserSync.watch. BrowserSync's documentation indicates that this feature requires at least version 2.6.0. So you may need to update your version of BrowserSync if you are not using that version.
BrowserSync in the gulpfile below is not showing the changes made to index.html even after it says 'Reloading Browsers' in command line as well as the 'Connected to BrowserSync' notification in Chrome.
Another odd thing that's occurring is that after the third save of the index.jade file, the rendered website in Chrome completely disappears, nothing in the rendered DOM.
I've followed ShakyShane's recipe on github (with a few tweaks). It worked without the tweaks on another project I started, but I can't see what's wrong here.
My file structure is:
project-folder
/app
/css
/jade
/js
/sass
index.html
gulpfile.js
package.json
Any help would be greatly appreciated.
/***********************************************************************************
1. DEPENDENCIES
/***********************************************************************************/
var gulp = require ('gulp'), // gulp core
plumber = require ('gulp-plumber'), // disable interuption
jade = require ('gulp-jade'), // jade compiler
sass = require ('gulp-sass'), // sass compiler
autoprefixer = require ('gulp-autoprefixer'), // sets missinb browser prefixes
browserSync = require ('browser-sync'), // inject code to all devices
reload = browserSync.reload; // browser sync reload
/*********************************************************************************
2. FILE DESTINATIONS (RELATIVE TO ASSETS FOLDER)
**********************************************************************************/
var target = {
jadeSrc : 'app/jade/**/*.jade', // source of jade files
htmlDest : 'app/', // html file destination
sassSrc : 'app/sass/**/*.sass', // source of sass files
cssDest : 'app/css', // minified css destination
jsDest : 'dist/js' // where to put minified js
};
/**********************************************************************************
3. SASS TASK
***********************************************************************************/
gulp.task ('sass', function (){
gulp.src(target.sassSrc) // get the files
.pipe(plumber()) // make sure gulp keeps runnin on errors
.pipe(sass()) // compile all sass
.pipe(autoprefixer()) // complete css with correct vendor prefixes
.pipe(gulp.dest(target.cssDest)) // file destination
.pipe(reload({stream:true}));
});
/**********************************************************************************
4. JADE TASKS
**********************************************************************************/
gulp.task('jade', function(){
var YOUR_LOCALS = {};
gulp.src(target.jadeSrc)
.pipe(jade({
locals: YOUR_LOCALS,
pretty: true
}))
.pipe(gulp.dest(target.htmlDest))
});
// separate watcher for browser-sync reaction to '.jade' file changes
gulp.task('jade-watch', ['jade'], reload);
/**********************************************************************************
5. BUILD SEQUENCES
**********************************************************************************/
gulp.task('default', ['sass', 'jade'], function(){
browserSync({server: target.htmlDest});
gulp.watch(target.sassSrc, ['sass']);
gulp.watch(target.jadeSrc, ['jade-watch']);
});
So I have installed gulp in my angular project, this is my gulpfile.js at the moment:
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var templates = require('gulp-angular-templatecache');
var minifyHTML = require('gulp-minify-html');
// Minify and templateCache your Angular Templates
// Add a 'templates' module dependency to your app:
// var app = angular.module('appname', [ ... , 'templates']);
gulp.task('templates', function () {
gulp.src([
'./**/*.html',
'!./node_modules/**'
])
.pipe(minifyHTML({
quotes: true
}))
.pipe(templates('templates.js'))
.pipe(gulp.dest('tmp'));
});
// Concat and uglify all your JavaScript
gulp.task('default', ['templates'], function() {
gulp.src([
'./**/*.js',
'!./public/js/**/*.js',
'!./node_modules/**',
'!./gulpfile.js',
'!./dist/all.js'
])
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
When I run gulp default, everything succeeds. But how can I notice this exactly? I don't get the feeling that anything has changed, my js files still look the same.
This is my project structure:
As your gulp configuration specifies, you would have obtained a file named all.js inside your dist/ directory. This is the file that would contain your all *.js files minified code.
You should be including this inside your index.html
Your original js files are untouched. There is template.js under "tmp" folder and all.js under "dist" folder. Those files are minimized.
you can use
gulp build
that will give you a minified js inside a dist.zip
more info click here