I'm trying to use Watch to compile my SASS files, but it doesn't work.
Package.json
"author": "José Ramón Rico Lara",
"license": "ISC",
"devDependencies": {
"gulp": "^4.0.2",
"gulp-concat": "^2.6.1",
"gulp-imagemin": "^7.1.0",
"gulp-notify": "^3.2.0",
"gulp-sass": "^4.1.0",
"gulp-webp": "^4.0.1"
}
}
Gulpfile.js
const { series, src, watch, dest, parallel } = require('gulp');
const sass = require('gulp-sass')
const webp = require('gulp-webp');
const paths = {
scss: 'src/scss/**/*.scss',
js: 'src/js/**/*.js'
}
function css() {
return src(paths.scss)
.pipe(sass())
.pipe(dest('./build/css'))
}
function javascript() {
return src(paths.js)
.pipe(concat('bundle.js'))
.pipe(dest('./build/js'))
}
function watchArchivos() {
watch(paths.scss, css); // * = La carpeta actual - ** = Todos los archivos con esa extensión
watch(paths.js, javascript);
}
exports.css = css;
exports.javascript = javascript;
exports.watchArchivos = watchArchivos;
exports.default = series(css, javascript, watchArchivos);
In the console it says, that the code is running and there isn't any issue, but when I change any file it doesn't compile it.
As far as I can tell there are no gulp.tasks... in example
gulp.task('watch', function() {
gulp.watch('public/assets/css/*.css', gulp.series('clean-css', 'pack-css'));
});
Also in the file you've supplied there's just exports, and you're not calling " watchArchivos".
Had a similar problem, the watching task never got executed, the first task in this case (browser) was a browser sync instance, in my case the browser task was asynchronous, so I had to use asyn / await and everything worked fine.
From:
function browser() {
browserSync.init({
server: {
baseDir: PATHS.output,
},
});
}
exports.default = series (browser, watching);
To
async function browser() {
await browserSync.init({
server: {
baseDir: PATHS.output,
},
});
}
Related
I'm having some problems with gulp with the generated minified files... The following section:
for (const counter of counters) {
//...
}
Is being minified as:
for(const n of n){/**etc...*/}
Which brings problems of variable initialization...
My package.json is using these dependencies:
"devDependencies": {
"del": "^3.0.0",
"gulp": "^4.0.0",
"gulp-concat": "^2.6.1",
"gulp-cssmin": "^0.2.0",
"gulp-htmlmin": "^3.0.0",
"gulp-terser": "^1.4.0",
"gulp-uglify": "^3.0.0",
"merge-stream": "^1.0.1"
}
And the gulpfile.js looks as follow:
'use strict';
var gulp = require('gulp'),
concat = require('gulp-concat'),
cssmin = require('gulp-cssmin'),
htmlmin = require('gulp-htmlmin'),
uglify = require('gulp-uglify'),
merge = require('merge-stream'),
del = require('del'),
bundleconfig = require('./bundleconfig.json'); // this file contains the route for the original js files
const terser = require('gulp-terser');
const regex = {
js: /\.js$/
};
// I've removed css and html minification operations
gulp.task('min:js', async function () {
merge(getBundles(regex.js).map(bundle => {
return gulp.src(bundle.inputFiles, { base: '.' })
.pipe(concat(bundle.outputFileName))
.pipe(terser())
.pipe(gulp.dest('.'));
}))
});
gulp.task('min', gulp.series(['min:js']));
gulp.task('clean', () => {
return del(bundleconfig.map(bundle => bundle.outputFileName));
});
gulp.task('watch', () => {
getBundles(regex.js).forEach(
bundle => gulp.watch(bundle.inputFiles, gulp.series(["min:js"])));
});
const getBundles = (regexPattern) => {
return bundleconfig.filter(bundle => {
return regexPattern.test(bundle.outputFileName);
});
};
gulp.task('default', gulp.series("min"));
I don't know why the minified file is like that, I tried to minify the same file using https://javascript-minifier.com/ and this problem isn't there.
Looks like your code is being mangled by the terser. Set the mangle flag to false and your problem should be solved.
You can refer to how to disable the flag here: https://www.npmjs.com/package/terser
When I'm trying to run the gulp default command on git bash an error occurred!
AssertionError [ERR_ASSERTION]: Task function must be specified
at Gulp.set [as _setTask] (C:\wamp64\www\WP-PROJECTS\thfireplaces.ca\demo_new\wp-content\themes\thfireplaces\node_modules\undertaker\lib\set-task.js:10:3)
at Gulp.task (C:\wamp64\www\WP-PROJECTS\thfireplaces.ca\demo_new\wp-content\themes\thfireplaces\node_modules\undertaker\lib\task.js:13:8)
at Object. (C:\wamp64\www\WP-PROJECTS\thfireplaces.ca\demo_new\wp-content\themes\thfireplaces\gulpfile.js:181:6)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (internal/modules/cjs/helpers.js:74:18)
at requireOrImport (C:\Users\Momin Riyadh\AppData\Roaming\npm\node_modules\gulp\node_modules\gulp-cli\lib\shared\require-or-import.js:19:11) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '=='
}
Here is my machine details node version 12.14.1 npm version 7.0.2 gulp local version 4.0.2!
package.json
{
"name": "instaHtmlQuickPack",
"version": "0.6.5",
"description": "Html Quick Pack",
"main": "index.js",
"scripts": {
"postinstall": "gulp default"
},
"engines": {
"npm": ">=2.1.8"
},
"repository": {
"type": "git",
"url": "#"
},
"keywords": [
"wordpress",
"theme",
"bootstrap"
],
"author": "Azizul Hoq",
"license": "GPL-2.0",
"bugs": {
"url": "#"
},
"homepage": "#",
"dependencies": {
"bootstrap": "4.3.1",
"browser-sync": "^2.18.12",
"del": "^3.0.0",
"gulp": "^4.0.0",
"gulp-clean-css": "^3.7.0",
"gulp-clone": "^1.0.0",
"gulp-concat": "^2.6.1",
"gulp-cssnano": "^2.1.2",
"gulp-ignore": "^2.0.2",
"gulp-imagemin": "^3.3.0",
"gulp-merge": "^0.1.1",
"gulp-plumber": "^1.1.0",
"gulp-rename": "^1.2.2",
"gulp-rimraf": "^0.2.1",
"gulp-sass": "^3.1.0",
"gulp-sequence": "^0.4.6",
"gulp-sourcemaps": "2.6.0",
"gulp-uglify": "^3.0.0",
"gulp-watch": "^4.3.11",
"jquery": "3.2.1",
"merge2": "^1.1.0",
"popper.js": "^1.11.1",
"run-sequence": "^2.0.0"
},
"devDependencies": {
"gulp-autoprefixer": "^4.0.0",
"gulp-csscomb": "^3.0.8",
"gulp-filenames": "^4.0.1"
}
}
gulpfile.js
// Defining base pathes
var basePaths = {
node: './node_modules/',
src: './src/',
assets: './assets/',
vendorsCss: './src/vendors/css/',
vendorsJs: './src/vendors/js/'
};
var jsFileList = [
basePaths.vendorsJs+'*.js',
basePaths.src+'js/custom-script.js'
];
var cssFileList = [
basePaths.vendorsCss+'*.css'
];
// console.log(jsFileList);
// Defining requirements
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var minifyCSS = require('gulp-cssnano');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var merge2 = require('merge2');
var ignore = require('gulp-ignore');
var del = require('del');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var csscomb = require('gulp-csscomb');
var imagemin = require('gulp-imagemin');
var browserSync = require('browser-sync').create();
// browser-sync watched files
// automatically reloads the page when files changed
var browserSyncWatchFiles = [
basePaths.assets+'css/*.css',
basePaths.assets+'js/*.js',
basePaths.src+'media/**',
'./*.html',
'./*.php'
];
var browserSyncOptions = {
proxy: "http://localhost/WP-PROJECTS/thfireplaces.ca/demo_new/",
notify: false
};
// Run:
// gulp browser-sync
// Starts browser-sync task for starting the server.
gulp.task('browser-sync', function() {
browserSync.init(browserSyncWatchFiles, browserSyncOptions);
});
// Run:
// gulp sass
// Compiles SCSS files in CSS
gulp.task('sass', function () {
gulp.src(basePaths.src+'sass/*.scss')
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(autoprefixer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('.'))
// .pipe(csscomb())
.pipe(gulp.dest(basePaths.assets+'css'))
.pipe(browserSync.stream());
});
// Run:
// gulp concat-css
// concat css file from src
gulp.task('concat-css', function() {
return gulp.src(cssFileList)
.pipe(plumber())
.pipe(concat('bundle.css'))
.pipe(gulp.dest(basePaths.assets+'css/'))
.pipe(browserSync.stream());
});
// Run:
// gulp concat-js
// concat js file from src
gulp.task('concat-js', function() {
return gulp.src(jsFileList)
.pipe(plumber())
.pipe(concat('bundle.js'))
.pipe(gulp.dest(basePaths.assets+'js/'))
.pipe(browserSync.stream());
});
// Run:
// gulp minifycss
// Minifies CSS files
gulp.task('minifycss', function(){
return gulp.src([basePaths.assets+'css/bundle.css', basePaths.assets+'css/theme.css'])
.pipe(plumber())
.pipe(concat('theme.min.css'))
.pipe(minifyCSS({keepBreaks:false,safe: true}))
.pipe(minifyCSS({
reduceIdents: {
keyframes: false
},
discardUnused: {
keyframes: false
},
discardComments: {
removeAll: true
}
}
))
.pipe(gulp.dest(basePaths.assets+'css/'));
});
// Run:
// gulp minifyjs
// Minifies js files
gulp.task('minifyjs', function() {
return gulp.src(basePaths.assets+'js/bundle.js')
.pipe(plumber())
// .pipe(concat('bundle.min.js'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest(basePaths.assets+'js/'));
});
// Run:
// gulp clean
// Remove file
gulp.task('clean', function () {
return del([
'css/*',
// here we use a globbing pattern to match everything inside the `mobile` folder
'js/*.js',
// we don't want to clean this file though so we negate the pattern
'!css/*.min.css',
'!js/*.min.js'
]);
});
// Run:
// gulp imagemin
// Running image optimizing task
gulp.task('imagemin', function(){
gulp.src(basePaths.src+'img/**')
.pipe(imagemin())
.pipe(gulp.dest(basePaths.assets+'img/'))
});
// Run:
// gulp watch
// Starts watcher. Watcher runs gulp sass task on changes
gulp.task('watch', function () {
// gulp.watch(basePaths.src+'sass/**/*.scss', ['sass']);
gulp.watch(basePaths.src+'sass/**/*.scss', gulp.series('sass'));
gulp.watch(cssFileList,gulp.series('concat-css'));
gulp.watch(jsFileList,gulp.series('concat-js'));
gulp.watch(basePaths.src+'img/**', gulp.series('imagemin'));
//gulp.watch('browser-sync');
});
//task register
// gulp.task('default', ['watch', 'sass', 'concat-css', 'concat-js', 'browser-sync']);
// gulp.task('build', ['sass', 'concat-css', 'concat-js', 'minifycss', 'minifyjs', 'imagemin']);
gulp.task('default', gulp.series('watch', 'sass', 'concat-css', 'concat-js', 'browser-sync'));
gulp.task('build', gulp.series('sass', 'concat-css', 'concat-js', 'minifycss', 'minifyjs', 'imagemin'));
The error I receive is:
Error: Cannot find module 'jquery' from 'F:...\newstyle\assets\lib\helper\html\img\js'
at
C:\Users...\AppData\Roaming\npm\node_modules\browserify\node_modules\browser-resolve\node_modules\resolve\lib\async.js:46:17
at process (C:\Users...\AppData\Roaming\npm\node_modules\browserify\node_modules\browser-resolve\node_modules\resolve\lib\async.js:173:43)
at ondir (C:\Users...\AppData\Roaming\npm\node_modules\browserify\node_modules\browser-resolve\node_modules\resolve\lib\async.js:188:17)
at load (C:\Users...\AppData\Roaming\npm\node_modules\browserify\node_modules\browser-resolve\node_modules\resolve\lib\async.js:69:43)
at onex (C:\Users...\AppData\Roaming\npm\node_modules\browserify\node_modules\browser-resolve\node_modules\resolve\lib\async.js:92:31)
at C:\Users...\AppData\Roaming\npm\node_modules\browserify\node_modules\browser-resolve\node_modules\resolve\lib\async.js:22:47
at FSReqWrap.oncomplete (fs.js:153:21)
My directory structure is as follows:
newstyle/assets/npm/index.js
newstyle/assets/npm/package.json
newstyle/assets/npm/gulpfile.js
newstyle/assets/lib/helper/html/img/js/img.module.js
My package.json looks like this:
{
"name": "newstyle",
"version": "1.0.0",
"description": "styles and libraries",
"main": "index.js",
"dependencies": {
"#tschallacka/assetmanager": "^1.0.0",
"#tschallacka/jquery.oc.foundation": "^1.0.2",
"#tschallacka/jquery.render": "^1.0.0",
"#tschallacka/jquery.request": "^1.0.0",
"#tschallacka/oc.foundation.base": "^1.0.1",
"#tschallacka/oc.foundation.controlutils": "^1.0.1",
"#tschallacka/oc.foundation.request": "^1.0.0",
"animate.css": "^3.7.0",
"bootstrap-less": "^3.3.8",
"flexslider": "^2.7.2",
"font-awesome": "^4.7.0",
"jquery": "^3.4.1",
"jquery-touchswipe": "^1.6.19",
"jquery.easing": "^1.4.1",
"lazysizes": "^4.1.8",
"liquidslider": "git+https://git#github.com/KevinBatdorf/liquidslider.git",
"popper.js": "^1.15.0",
"sweetalert2": "^8.11.1"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
My index.js like this:
require('#tschallacka/oc.foundation.base');
require('#tschallacka/oc.foundation.controlutils');
// ====================== TROUBLE CAUSING LINE!! ==========================
require('../assets/lib/helper/html/img/js/img.module.js');
the code in newstyle/assets/lib/helper/html/img/js/img.module.js
var $ = require('jquery');
var Base = require('#tschallacka/oc.foundation.base');
var controlUtils = require('#tschallacka/oc.foundation.controlutils');
My gulpfile.js
'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var log = require('gulplog');
var less = require('gulp-less');
var cssmin = require('gulp-cssmin');
var rename = require('gulp-rename');
gulp.task('javascript', function () {
// set up the browserify instance on a task basis
var b = browserify({
entries: './index.js', // Source name
debug: true
});
return b.bundle()
.pipe(source('closure.js'))// Resulting filename
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.on('error', log.error)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('../js/'));
});
gulp.task('watch', function () {
gulp.watch('./*.less', ['less']);
});
gulp.task('less', function () {
return gulp.src('./style.less')
.pipe(less({
relativeUrls: true
}).on('error', function (err) {
console.log(err);
}))
.pipe(cssmin().on('error', function(err) {
console.log(err);
}))
.pipe(rename('closure.css'))
.pipe(gulp.dest('../css/'));
});
When I run this without the trouble causing line, everything works fine, it finds the modules and it compiles without a hitch. No problems with not finding the modules.
But when I require that script, the module I required as test from the "parent" script suddenly cannot be found anymore, even though it should still be in the cache by string name.
It does work if I 'require' the files by filename, but that's less than desirable because then I constantly need to check directory nesting.
What causes this and how can I resolve this?
Things I've tried:
setting basedir
var b = browserify({
entries: './index.js', // Source name
debug: true,
basedir: __dirname
});
npm update from 6.4.1 to 6.9.0
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade
updated gulp:
+ gulp#4.0.2
updated 6 packages in 19.938s
The solution is rather simple, but not easy to get to the conclusion what causes the error, you have to add node_modules to the 'paths' variable of browserify in your gulpfile.js
// set up the browserify instance on a task basis
var b = browserify({
entries: './index.js', // Source name
debug: true,
paths: ['./node_modules'] // <--- this line here
});
I'm using gulp babel to compile es6, but it seems like uglify is stripping out my es6 altogether. I'm not getting any errors in my command line when this runs. Any ideas why this is getting stripped out?
My gulp task looks like this:
gulp.task('scripts', function () {
return gulp.src('src/js/*.js')
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(uglify())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist/js'));
});
My javascript:
document.addEventListener('DOMContentLoaded', function (event) {
console.log('ready to es6!');
const foo = 4;
});
The outputted, compiled/uglified javascript:
"use strict";document.addEventListener("DOMContentLoaded",function(e){console.log("ready to es6!")});
//# sourceMappingURL=scripts.js.map
Notice the const foo = 4 is left out. Removing the .pipe(babel()) results in the const getting compiled properly.
If it's helpful, devDependencies:
"devDependencies": {
"#babel/core": "^7.2.2",
"#babel/preset-env": "^7.2.3",
"browser-sync": "^2.26.3",
"gulp": "^3.9.1",
"gulp-babel": "^8.0.0-beta.2",
"gulp-sass": "^4.0.2",
"gulp-sourcemaps": "^2.6.4",
"gulp-uglify": "^3.0.1",
"node-sass": "^4.11.0"
}
UglifyJS (a dependency of gulp-uglify) has a Compress option that by default removes unused vars. Since you never reference foo it is removed from the compressed source.
From UglifyJS2 docs:
Compress options:
unused (default: true) -- drop unreferenced functions and variables (simple direct variable assignments do not count as references unless set to "keep_assign")
Since const foo = 4 is a simple direct variable assignment it doesn't appear in your compressed code. You can either assume you don't need the unused code or adjust your gulp file as such:
gulp.task('scripts', function () {
return gulp.src('src/js/*.js')
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(uglify({
compress: {
unused: false
}
}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist/js'));
});
I had a similar question here that has merged into a bit more research on my part and a new way this could work.
Basically I'm trying to have all of my .js and .coffee files within one gulp.src() object and based on the extension, do relevant tasks.
What started off with gulp-if has turned into me using gulp-filter which I prefer honestly. The catch I'm running into right now is getting this all to work with gulp-sourcemaps. The current task seems to override the other -- but I'd ultimately like everything to be concatenated in one file, source-mapped in another and have each file extension run its respective tasks. You'll see the uglify task is commented out; as that's what keeps yelling at me; without a whole bunch to go off of. When I do get the filters to work and I have a CoffeeScript error, I noticed that coffeescriptlint() will do its job, but then my watch command; while still running, doesn't respond to anything.
It seems like I might be going down the path of extracting each sourcemap using something like gulp-extract-sourcemap, but am not sure if that's the right way to go.
Normally I'd separate out the JS and Coffeescript task, but I have so many things co-mingling between the two that bringing them together with a simple filter seemed logical -- especially as I'm trying to figure out the sourcemaps for both.
I feel like this one is pretty close, so any nudges in the right direction would be greatly appreciated. Included current gulpfile.js and package.json if you want to spin it up. Thanks!
Gulpfile.js
// Load plugins
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
coffee = require('gulp-coffee'),
changed = require('gulp-changed'),
coffeelint = require('gulp-coffeelint'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
notify = require('gulp-notify'),
concat = require('gulp-concat'),
filesize = require('gulp-size'),
livereload = require('gulp-livereload'),
duration = require('gulp-duration'),
gutil = require('gulp-util'),
gFilter = require('gulp-filter');
gulp.task('scripts', function() {
var jsBuildDir = 'assets/js/build/',
jsFilter = gFilter('**/*.js'),
coffeeFilter = gFilter('**/*.coffee');
return gulp.src([
'assets/js/src/_init.coffee',
'assets/js/src/_init.js'
])
.pipe(coffeeFilter)
.pipe(coffeelint().on('error', gutil.log))
.pipe(coffeelint.reporter())
.pipe(sourcemaps.init())
.pipe(coffee({bare: true}).on('error', gutil.log))
.pipe(sourcemaps.write('../../maps'))
.pipe(coffeeFilter.restore())
.pipe(jsFilter)
.pipe(jshint({
'boss': true,
'sub': true,
'evil': true,
'browser': true,
'globals': {
'module': false,
'require': true
}
}),
jshint.reporter('jshint-stylish'))
.pipe(jsFilter.restore())
.pipe(concat('scripts.min.js'))
//.pipe(uglify())
.pipe(filesize({
title: 'Scripts:'
}))
.pipe(gulp.dest(jsBuildDir))
.pipe(duration('building script files'))
.pipe(notify({ message: 'Coffeescript task complete' }));
});
// Default task
gulp.task('default', ['scripts']);
// Watch
gulp.task('watch', function() {
gulp.watch(['assets/js/src/**/*.js', 'assets/js/src/**/*.coffee'], ['scripts']);
// Create LiveReload server
var server = livereload();
// Watch files in patterns below, reload on change
gulp.watch(['assets/js/build/*']).on('change', function(file) {
server.changed(file.path);
});
});
Package.json
{
"devDependencies": {
"gulp": "^3.8.8",
"gulp-changed": "^1.0.0",
"gulp-coffee": "^2.2.0",
"gulp-coffeelint": "^0.4.0",
"gulp-concat": "^2.4.0",
"gulp-duration": "0.0.0",
"gulp-filter": "^1.0.2",
"gulp-jshint": "^1.8.4",
"gulp-livereload": "^2.1.1",
"gulp-notify": "^1.6.0",
"gulp-size": "^1.1.0",
"gulp-sourcemaps": "^1.2.2",
"gulp-uglify": "^1.0.1",
"gulp-util": "^3.0.1",
"jshint-stylish": "^0.4.0"
}
}
I guess you wrapped the sourcemaps.init() and sourcemaps.write() around the wrong section of your pipe. I put the commands where I assume they belong. See below.
I used gulp-filter quite a few times as well. However, I kept it to a minimum to not overcomplicate things. I found run-sequence very helpful. (Also check out some of my gulpfiles here and here.)
Your scenario I would approach like this:
var runSequence = require('run-sequence');
// ...
gulp.task('scripts', function (done) {
runSequence('lint', 'build', done);
});
gulp.task('lint', function (done) {
runSequence('lint-coffee', 'lint-js', done);
});
gulp.task('lint-coffee', function () {
// Just lint your coffee files here...
});
gulp.task('lint-js', function () {
// Just lint your js files here...
});
gulp.task('build', function () {
return gulp.src([
'assets/js/src/_init.coffee',
'assets/js/src/_init.js'
])
.pipe(coffeeFilter)
.pipe(coffee({bare: true}).on('error', gutil.log))
.pipe(coffeeFilter.restore())
.pipe(sourcemaps.init())
.pipe(concat('scripts.min.js'))
.pipe(uglify())
.pipe(sourcemaps.write('../../maps'))
.pipe(gulp.dest(jsBuildDir));
});