The following is my simple gulp task:
gulp.src is getting script.js as input
minifies script.js and saves script.min.js
removes console.log from both script.js and script.min.js
updates script.js file and saves script.min.js
I want to simply remove console.log from a minified file (or script.min.js) not from script.js, and I am failing. I am looking for a way to run .pipe(gulpRemoveLogging... only on a minified file (i.e. script.min.js) and do not modify anything from script.js
var gulp = require("gulp"),
minify = require("gulp-minify"),
gulpRemoveLogging = require("gulp-remove-logging");
var _dist_path = "./dist/"; // relative path
// minify JS files
gulp.task("minify-js", function() {
return gulp.src(path.join(_dist_path, "/*.js"))
.pipe(minify({
ext: {
src: ".js",
min: ".min.js"
},
ignoreFiles: ["-min.js"]
}))
.pipe(gulpRemoveLogging({
namespace: ["console", "window.console"] // remove these namespaces. e.g. console.log("..."), window.console.log("...")
}))
.pipe(gulp.dest(_dist_path));
});
Solved the problem:
Added .pipe(gulpIgnore("smartsitescripts.js")) between .pipe(minify({ ... and .pipe(gulpRemoveLogging ...
var gulpIgnore = require("gulp-ignore");
...
.pipe(minify({
ext: {
src: ".js",
min: ".min.js"
},
ignoreFiles: ["-min.js"]
}))
.pipe(gulpIgnore("script.js")) // <---- this line solved the problem
.pipe(gulpRemoveLogging({
namespace: ["console", "window.console"] // remove these namespaces. e.g. console.log("..."), window.console.log("...")
}))
...
That line of code will exclude script.js from stream hence stream will contain only script.min.js.
Related
i have a problem with my gulp.
Its works fine and its really fast but Gulp is compiling all js files in my project...
my gulp-watch:
gulp.task('watch', function () {
gulp.watch(sassFilesWatch, ['styles']);
gulp.watch(jsFilesWatch, ['uglify'])
});
My array:
var jsFilesWatch = [
'clients/*/template/lib/jscripts/*.js',
'clients/*/template/modules/**/*.js',
'system/lib/jscripts/*.js',
'system/mod/**/*.js',
'clients/core/modules/**/*.js',
'!/**/*.min.js'
];
Thats my function:
gulp.task('uglify', function(){
pump([
gulp.src(jsFilesWatch, {
base: './'
}),
debug({
title: 'Compiled',
showFiles: false,
}),
uglify(),
rename({ suffix: '.min' }),
gulp.dest('./')
]);
});
And thats the output:
Output
Just my saved file should be compiled
how can i do that?
thanks alot
It seems all your files with .js extensions are
being debugged, uglified and minified.
Which saved file are you trying to compile?
**/*.js uses the gulp command to watch all files with the .js extension in all folders.
You could use .pipe()
var uglify = require('gulp-uglify'),
concat = require('gulp-concat');
gulp.task('js', function() {
gulp.src('scripts/*.js')
.pipe(uglify())
.pipe(concat('script.js'))
.pipe(gulp.dest('assets'))
});
Have a look into this Plugin, That will solve your problem
https://www.npmjs.com/package/gulp-changed
Try Changing your task to,
gulp.task('uglify', function(){
pump([
gulp.src(jsFilesWatch, {
base: './'
}),
changed('dist'),
ngAnnotate(),
debug({
title: 'Compiled',
showFiles: false,
}),
uglify(),
rename({ suffix: '.min' }),
gulp.dest('./')
]);
});
Note: this might run all your .js files at first time after you run your task, but it will identify the changed file on subsequent runs
I have a project where I'm using Angular 1.6 and I'm using angular-translate to internationalize the project.
Angular-translate is installed, configured and working, If I add some text like:
{{'Test' | translate}}
<span translate>Test</span>
and manually add the key "Test" into the files es.json and en.json, Angular translate the keys without problems.
Now I'm trying to automatize the process of extracting all the translated keys from the HTML and JS files.
I've been digging around and found this 2 packages:
gulp-angular-translate-extract
gulp-angular-translate-extractor
My gulpfile.js has a task called "watch", this task is watching the JS & HTML files for changes. My idea is to have another task "translation" that is called within the watch task.
I tried to create the task "translation" with the 2 libraries mentioned above. I tried several configurations with those libraries but none of those libraries extracted the translations and added them into en.json & es.json.
This are small examples of what I tried:
gulp-angular-translate-extract
var angularTranslate = require('gulp-angular-translate-extract');
gulp.task('translate', function () {
return gulp.src(['./src/app/**/*.html', './src/app/**/*.js'])
.pipe(angularTranslate({
lang: ['en', 'es'],
dest: 'src/app/locale/',
suffix: '.json',
prefix: '',
}))
});
gulp-angular-translate-extractor
var extractTranslate = require('gulp-angular-translate-extractor');
gulp.task('taskName', function () {
var i18nsrc = ['./src/app/**/*.html', './src/app/**/*.js']; // your source files
var i18ndest = './src/app/locale'; //destination directory
return gulp.src(i18nsrc)
.pipe(extractTranslate({
defaultLang: 'en',
lang: ['en', 'es'],
dest: i18ndest,
prefix: '',
suffix: '.json',
safeMode: false,
stringifyOptions: true,
}))
.pipe(gulp.dest(i18ndest));
});
With the above configuration the translation task is called every time I modified an HTML or JS file, but the translation keys are not extracted, I mean the keys of the translations are not automatically added to the es.json and en.json
What am I missing here ? Am I missing some extra gulp configuration ?
Solved ! I manage to make it works using the package gulp-angular-translate-extractor
It seems the main issue there was the relative paths:
# Source paths
./src/app/**/*.html
./src/app/**/*.js
# Dest paths
./src/app/locale
I update the configuration to use the next paths and the translations are extracted without problems:
var extractTranslate = require('gulp-angular-translate-extractor');
gulp.task('translate', function () {
var i18nsrc = [path.join(conf.paths.src, '/app/**/*.html'), path.join(conf.paths.src, '/app/**/*.js')]; // your source files
var i18ndest = path.join(conf.paths.src, '/app/locale/')
return gulp.src(i18nsrc)
.pipe(extractTranslate({
defaultLang: 'en',
lang: ['en', 'es'],
dest: i18ndest,
prefix: '',
suffix: '.json',
safeMode: false,
stringifyOptions: true,
}))
.pipe(gulp.dest(i18ndest));
});
The main difference with the code of my question is that I used the next paths:
# Source paths
path.join(conf.paths.src, '/app/**/*.html')
path.join(conf.paths.src, '/app/**/*.js')
# Dest paths
path.join(conf.paths.src, './src/app/locale')
Being the variable conf.paths.src like:
conf.js
exports.paths = {
src: 'src',
dist: 'release',
devDist: 'dev-release',
tmp: '.tmp',
e2e: 'e2e'
};
EDIT: upon further reflection I believe my question is about grunt-contrib-concat rather than sass.
I have a folder of sass files one of which is called colors.scss
//neutrals
$white: #fff;
$light-gray: #eee;
$gray: #9f9f9f;
$slate: #59595A;
$charcoal: #404041;
$gold: #FFD34E;
//define non-neutral colors by use. These are what would change if our app was whitelabeled.
$bright-accent-color: tint(#FF4849, 0%);
$muted-accent-color: $bright-accent-color;
$dark-accent-color: $bright-accent-color;
$note-color: #FFFAD5;
$bright-warning-color: black; // will this be used in new scheme?
$muted-warning-color: tint(#DB9E36, 20%);
$dark-warning-color: $charcoal;
$light-background-color: #f3f6f9;
$primary-nav-color: #172740; // dark blue
$secondary-nav-color: #263D59; // blue
I would like to produce a dozen sets of compiled css files, of which I would swap out the colors.css file for each compiled set. I'm trying to figure out how to incorporate this into my gruntfile without producing seperate tasks for each one. I would like one task that looks in folder called colors that in turn contains all of the colors.scss files and then for each one does a compilation and puts that compiled set of css files in a folder with the same name as the colors.scss file. The problem is I have no idea where to start. I'm using grunt-contrib-sass currently and I'm able to produce one set of files. My gruntfile looks like this:
sass: {
dist: {
options: {
style: 'expanded'
},
files: {
'dist/main.css': 'app/css/main.scss'
}
}
},
which works fine for compiling one set, but I want to iterate over the colors files and produce one set for each file found. is this possible? where should I start?
Think I got it. I edited my gruntfile with the following modules: sass, concat, and copy.
In summary, I concat the specific brand scss file to the main scss file and then copy all of the support files to a sass folder in the dist directory. Then I run sass on the concat'd files and output the final css files to the dist css folder.
Heres the configuration:
module.exports = function(grunt) {
'use strict';
var sassFiles = [];
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.registerTask('default', ['concat', 'copy:sass', 'sass']);
grunt.initConfig({
concat: (function(){
var concat = {
options: {
sourceMap: true
}
};
var files = [];
grunt.file.recurse('app/css/brands/', function(abspath, rootdir, subdir, filename){
files.push(filename);
});
sassFiles = files;
files.forEach(file => {
concat[file] = {
src: [
'app/css/brands/'+file,
'app/css/main.scss'
],
dest: 'dist/css/sass/'+file
};
});
return concat;
}()),
sass: {
dist: {
options: {
style: 'expanded'
},
files: (function(){
var fileObject = {};
sassFiles.forEach(file => {
var filename = file.split('.')[0];
fileObject['dist/css/'+filename+'.css'] =
'dist/css/sass/'+file;
});
return fileObject;
}())
}
},
copy: {
sass: {
files: [
{ expand: true, cwd: 'app/css', src: '**', dest: 'dist/css/sass/' }
]
}
}
});
};
I have the following gulp task, basically what it does is:
compile all .styl files
put the result in theme/app folder
minify all file in theme/app folder
concatenate all file in folder theme/app folder to a single file
add some license information to the file
save result in foldertheme
delete all files in theme/app folder
I cannot make work the last step, I need to delete all files in theme/app.
I have not specific error, what could could be wrong in my script and how to solve it?
gulp.task('_release-theme:compile', function () {
gulp.src([
'app/**/*.styl',
'!app/**/**mixins**.styl',
'!app/**/**variables**.styl',
])
.pipe(stylus({
compress: false,
use: nib()
}))
.pipe(gulp.dest('theme/app'))
.pipe(cleanCSS())
.pipe(concat('theme.css'))
.pipe(header(fs.readFileSync('licenses/app.txt', 'utf8')))
.pipe(gulp.dest('theme/'))
.pipe(vinylPaths(del['theme/app/**/*'])); // problem here
});
del is a function. Your object property access del['theme/app/**/*'] makes no sense here.
Instead listen for the end event in your stream and then delete the files using rimraf:
var rimraf = require('rimraf');
gulp.task('_release-theme:compile', function (done) {
gulp.src([
'app/**/*.styl',
'!app/**/**mixins**.styl',
'!app/**/**variables**.styl',
])
.pipe(stylus({
compress: false,
use: nib()
}))
.pipe(gulp.dest('theme/app'))
.pipe(cleanCSS())
.pipe(concat('theme.css'))
.pipe(header(fs.readFileSync('licenses/app.txt', 'utf8')))
.pipe(gulp.dest('theme/'))
.on('end', function() {
rimraf('theme/app/**/*', done);
});
});
I'm trying to compile all my scripts into a single main.js file which I can then link to my index file. Problem is that all my script files are being concatenated and then just added to the main.js file, so if I save 3 times, I will basically have 3 copies of all my scripts concatenated and put in the main.js file.
I would like to either delete the main.js file each time I save and then run the concatenation, or just clean the file before adding the contents. Now if I try to delete the file using the del module, I receive an error stating that I can't delete files out of the working directory without forcing this action. I would like to avoid forcing this if possible.
I feel that there must be a more elegant way of doing this..
Here's my script task:
// Concat and compile our JS into a minified dist file
gulp.task('scripts', function() {
return gulp.src('../app/public/assets/scripts/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(concat('main.js'))
//.pipe(del(['../app/public/assets/scripts/main.js'])) <-- Doesn't work without forcing
.pipe(gulp.dest('../app/public/assets/scripts'))
.pipe(gulpif(flags.build, gulp.dest('../app/dist/assets/scripts')))
.pipe(rename({ suffix: '.min' }))
.pipe(uglify())
.pipe(gulpif(flags.build, gulp.dest('../app/dist/assets/scripts')))
.pipe(notify({ message: 'Finished compiling scripts' }));
});
I usually do something like this (very simplified :) ):
var PARAMS = {
destPath: 'build',
js: [
'src/js/test1.js',
'src/js/test2.js',
// ecc...
],
// other
};
var TARGETS = {
dest: 'main.js', // dest file
extra: [
// This files are inclued only in .bundle.min.js version
// extra file here
],
js: [
'src/js/test1.js',
'src/js/test2.js',
// ecc...
]
};
gulp.task('connect', function() {
return connect.server({
livereload: true,
host: '0.0.0.0',
port: 8000
});
});
gulp.task('reload', ['build'], function () {
return gulp.src(['sandbox/**/*.html'])
.pipe(connect.reload());
});
gulp.task('watch', ['connect', 'build'], function () {
var src = [];
// other
src = src.concat(PARAMS.js);
return gulp.watch(src, ['reload']);
});
gulp.task('clean', function (done) {
return del(['build'], done);
});
gulp.task('build', ['clean'], function () {
return gulp.src(target.js);
.pipe(concat(target.dest))
.pipe(gulp.dest(PARAMS.destPath)) // Plain
.pipe(uglify())
.pipe(rename({ extname: '.min.js' })) // Minified
.pipe(gulp.dest(PARAMS.destPath))
.pipe(addsrc(target.extra))
.pipe(order(target.extra))
.pipe(concat(target.dest))
.pipe(rename({ extname: '.bundled.min.js' })) // Bundled
.pipe(gulp.dest(PARAMS.destPath));
});
gulp.task('default', ['build']);