gulp-rev creates a directory inside the destination directory - javascript

First of all, I would like to say that Gulp (for me) is creating more problems instead of solving them.
I wrote a gulpfile that concat some CSS files and put them inside a directory. The code for this task is the following:
var config = {
mainDir: 'app/assets'
};
config.stylesFiles = [
'bower_resources/admin-lte/dist/css/AdminLTE.min.css',
'bower_resources/admin-lte/dist/css/skins/_all-skins.min.css',
'css/app.css'
];
....
gulp.task('styles', function() {
return gulp
.src(config.stylesFiles, { cwd: config.mainDir })
.pipe(sourcemaps.init())
.pipe(concat('theme.css'))
.pipe(sourcemaps.write('../build/css'))
.pipe(gulp.dest('public/css/'))
.on('end', function() { gutil.log('Styles copied') });
});
It is very simple and works perfectly.
But, I would like to version this generated file. So I wrote a specific task to do it:
....
config.manifestFolder = process.cwd() + '/public/build';
gulp.task('versionCSS', function() {
return gulp
.src(['css/theme.css'], { cwd: 'public' })
.pipe(rev())
.pipe(gulp.dest('public/build/css'))
.pipe(rev.manifest(
{
base: config.manifestFolder,
cwd: config.manifestFolder,
merge: true
}
))
.pipe(gulp.dest(config.manifestFolder))
.on('end', function() { gutil.log('CSS files versioned') });
});
The problem is: when Gulp is going to run this task, it creates a folder inside the destination folder.
After running Gulp, I get this structure:
- public
- build
- css (destination folder for the versioned file)
- css (folder created by Gulp)
- versioned file that should be in the parent folder
- css
- concatenated file without version
I really don't know what to do anymore. I've already set the cwd and base options for the dest and src functions, changed the destinations, synchronized the tasks, etc. Nothing solves this stupid behavior.

Related

Bundle .js and .css dependecies from package.json with gulp

I'm trying to convert an old project that uses Bower + gulp (+ npm) into something similar, which doesn't use Bower but keeps most of Gulp.
I'm stuck with reproducing the equivalent of wiredep, ie, picking all the relevant .js and .css from third party dependencies (which now are moved from Bower to package.json), to use them for either HTML injection or bundling all .js/.css into a single file.
Before, it was doing this, using a mix of wiredep and inject:
gulp.task('inject-html', ['compile-styles'], function () {
$.util.log('injecting JavaScript and CSS into the html files');
var injectStyles = gulp.src(config.outputCss, { read: false });
var injectScripts = gulp.src(config.js, { read: false });
var wiredepOptions = config.getWiredepDefaultOptions();
var injectOptions = {
ignorePath: ['src', '.tmp'], addRootSlash: false,
};
var wiredep = require('wiredep').stream;
return gulp.src(config.html)
.pipe(wiredep(wiredepOptions))
.pipe($.inject(injectStyles, injectOptions))
.pipe($.inject(injectScripts, injectOptions))
.pipe(gulp.dest(config.srcDir), {overwrite: true});
});
Now, I've managed to do this for the .js files:
gulp.task('bundle-deps', function () {
var deps = Object.keys(packageJson.dependencies)
.map(module => `node_modules/${module}/**/*.js`);
// set up the browserify instance on a task basis
var b = browserify({
entries: './package.json',
debug: true
});
return b.bundle()
.pipe(source('genemap-lib.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true})) // debug info for the browser
.pipe(uglify())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/js/'));
});
This works in building a single dependency .js. That's not like the injection above, but I'd be fine with it.
However, I can't find any way to do the same for the .css files, because this:
gulp.task('bundle-deps-css', function () {
var deps = Object.keys(packageJson.dependencies);
var depsCss = deps.map(module => `node_modules/${module}/**/*.css`);
return gulp.src( depsCss )
.pipe(concatCss("genemap-lib.css"))
.pipe(gulp.dest('dist/styles/'));
});
picks up some */demo/demo.css and then I get the error that it has a syntax error.
I'm thinking that the above methods are wrong, selecting all .js/.css is too dumb, there should be a way to select the library-exported files, not all that can be found in its directory (ie, the gulp equivalent of wiredep).
But how to do it? Is it possible with Gulp? Should I migrate to something like webpack? And Yarn too?

gulp.src from a separate file doesnt work

I am trying to write a gulpfile as follows :
var gulp = require('gulp');
// other dependencies go here ....
// source of files
var inputs = require('./asset_source.js');
// a simple task
gulp.task('css', function () {
gulp.src(inputs.css)
.pipe(debug())
.pipe(plumber())
.pipe(maps.init())
.pipe(concatCss('libs.css'))
.pipe(maps.write('../srcmaps'))
.pipe(plumber.stop())
.pipe(gulp.dest('assets/css'));
});
// the watcher
gulp.task('watch', function () {
gulp.watch('./asset_source.js', ['css']);
});
// default task
gulp.task('default', ['browser-sync', 'watch']);
And the source of assets (asset_source.js) file is something like this :
module.exports = {
css: [
'path/to/a/file.css',
'path/to/another/file.css',
.......
.......
],
js: [
'path/to/a/file.js',
'path/to/another/file.js',
.......
.......
]
};
Now I run the app with by just typing gulp in the console and it starts in a browser thanks to browsersync. I have all the css,scss,js assets listed in the asset_source.js file which is in the same directory as the gulpfile.js. What I want to achieve is if I append or remove a value to/from either of the arrays in asset_source.js, the concerned task should run while the gulp is already running. In this case css should be running on any change to asset_source.js with its updated content.
But instead it doesnt do so. Even if there is a change in the asset_source file, gulp uses the initial content and runs the task. However if run gulp css in a separate terminal, it works.
Please help me where I am going wrong or if it is even possible. Thanks.

gulp pipe(gulp.dest()) does not create any results

i am currently learning about gulp.js.
as i saw the tutorial and documentation of gulp.js, this code:
gulp.src('js/*.js')
.pipe(uglify())
.pipe(gulp.dest('minjs'));
makes the uglified javascript file with create new directory named 'minjs'. of course, i installed gulp-uglity with --dev-save option. there is no error message on the console so i don't know what is the problem. i tried gulp with "sudo", but still not working.
so i went to the root directory and searched all filesystem but there is no file named 'minjs' so i guess it just not working. why this is happening? anyone knows this problem, it would be nice why this is happening.
whole source code:
var gulp = require('gulp');
var uglify = require('gulp-uglify');
gulp.task('default', function() {
console.log('mifying scripts...');
gulp.src('js/*.js')
.pipe(uglify())
.pipe(gulp.dest('minjs'));
});
I had the same problem; you have to return the task inside the function:
gulp.task('default', function() {
return gulp.src("js/*.js")
.pipe(uglify())
.pipe(gulp.dest('minjs'));
Also, minjs will not be a file, but a folder, where all your minified files are going to be saved.
Finally, if you want to minify only 1 file, you can specify it directly, the same with the location of the destination.
For example:
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
gulp.task('browserify', function() {
return browserify('./src/client/app.js')
.bundle()
// Pass desired output filename to vinyl-source-stream
.pipe(source('main.js'))
// Start piping stream to tasks!
.pipe(gulp.dest('./public/'));
});
gulp.task('build', ['browserify'], function() {
return gulp.src("./public/main.js")
.pipe(uglify())
.pipe(gulp.dest('./public/'));
});
Hope it helps!
Finally I resolved the question like this:
It was a directory mistake so the gulp task hasn't matched any files; then it couldn't create the dest directory (because no files in output).
const paths = {
dest: {
lib: './lib',
esm: './esm',
dist: './dist',
},
styles: 'src/components/**/*.less',
scripts: ['src/components/**/*.{ts,tsx}', '!src/components/**/demo/*.{ts,tsx}'],
};
At first my scripts was ['components/**/*.{ts,tsx}', '!components/**/demo/*.{ts,tsx}']
And that hasn't matched any files.

Can browserify require a vinyl file generated in gulp?

I've just started using gulp and browserify and I need some help with this problem:
I'm using a lib called ng-autobootstrap to generate a browserify compatible file, which is later on required in the main script. Here's my autobootstrap task:
gulp.task "autobootstrap", ->
gulp.src("source/**/*.{coffee,js}",
read: false
base: "source"
)
.pipe(ngAutoBootstrap(
moduleTypes:
animation:
path: "**/animations/*.{coffee,js}",
constant:
path: "**/constants/*.{coffee,js}",
controller:
path: "**/controllers/*.{coffee,js}",
directive:
path: "**/directives/*.{coffee,js}",
factory:
path: "**/factories/*.{coffee,js}",
filter:
path: "**/filters/*.{coffee,js}",
provider:
path: "**/providers/*.{coffee,js}",
service:
path: "**/services/*.{coffee,js}",
value:
path: "**/values/*.{coffee,js}",
# config modules are pulled in like this:
# app.config(require("./path/to-config"))
config:
path: "**/*-config.{coffee,js}"
))
If I add .pipe(gulp.dest("./source/")), it will create a bootstrap.js file in the source directory, but this is not exactly what I want, I would rather keep that directory clean. As far as I understand, up to now I have a vinyl file in memory, with the following content:
'use strict';
module.exports = function(app) {
// Controllers
app.controller('AppController', require('./controllers/app-controller'));
app.controller('UsersController', require('./controllers/users-controller'));
// ... and so on
};
Let's suppose the source/js/main.js file looks like this:
app = angular.module("app");
require("./bootstrap")(app); // this is the file generated by ng-autobootstrap
And a simple browserify task which creates the build/bundle.js file:
browserify = require('browserify')
gulp = require('gulp')
source = require('vinyl-source-stream')
gulp.task 'browserify', ->
browserify('./source/main.js')
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./build/'))
Now, if I modify the autobootstrap to write the file to disc first, then run browserify, this is all fine, the ./bootstrap file will be there. But is there a way to avoid writing to disc? Something like adding a vinyl file to browserify's search tree?
Use b.require to make a file available from outside of the bundle. And in order to use the vinyl streams, that Gulp uses/emits, with Browserify; we make a small inline transform using through2.obj to emit only the contents.
A note on using b.require is that you need to b.exclude so that module-deps doesn't try to resolve it in the node_modules directories, etc. See issues #908 and #1106 for more information.
var gulp = require('gulp');
var through = require('through2');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
gulp.task('browserify-bundle', function() {
return browserify('./test/main.js')
// We need to exclude the required module so `module-deps` doesn't try to resolve it in the `node_modules` directories, etc
// Suggested here: https://github.com/substack/node-browserify/issues/908#issuecomment-74909062
// See also: https://github.com/substack/node-browserify/issues/1106
.exclude('some-func')
// Then add in the module to the bundle
.require(
gulp.src('./test/hidden-some-func.js')
// Any plugins here....
// .pipe(ngAutoBootstrap(..)
//
// Then convert it to a object stream with only the `contents` for browserify to consume
.pipe(through.obj(function(chunk, env, cb) {
if (chunk.isStream()) {
self.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Cannot operate on stream'));
}
else if (chunk.isBuffer()) {
this.push(chunk.contents);
}
// "call callback when the transform operation is complete."
cb();
})),
{
// Dependency name to inject
expose: 'some-func',
// So that relative requires will be resolvable
basedir: './test/'
}
)
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('dest'));
});

Gulpfile not watching scss

I have a simple gulpfile that loads a javascript object from a json file (to get paths based on environment), compiles my scss files, moves them to my public directory, and also moves any javascript files to the public directory.
So my assets in /app/Http/assets/js and scss
are compiled and moved to /public/assets/js and css
Here is my gulpfile.js:
var gulp = require('gulp');
var gutil = require('gulp-util');
var notify = require('gulp-notify');
var sass = require('gulp-sass');
var autoprefix = require('gulp-autoprefixer');
// Load the application config
var config = require('./env.config.json');
// Where do you store your Sass files?
var sassDir = 'app/Http/Assets/scss';
// Which directory should Sass compile to?
var targetCSSDir = config.assets_path + '/css';
// Where do you store your CoffeeScript files?
var jsDir = 'app/Http/Assets/js';
// Which directory should CoffeeScript compile to?
var targetJSDir = config.assets_path + '/js';
/** Tasks **/
// Compile Sass, autoprefix CSS3, and save to target CSS directory
gulp.task('css', function () {
return gulp.src(sassDir + '/**/*.scss')
.pipe(sass())
.pipe(autoprefix('last 10 version'))
.pipe(gulp.dest(targetCSSDir))
.pipe(notify('CSS minified'))
});
// Move Javascript
gulp.task('js', function () {
return gulp.src(jsDir + '/**/*.js')
.pipe(gulp.dest(targetJSDir))
});
// Keep an eye on Sass and Javascript files for changes...
gulp.task('watch', function () {
gulp.watch(sassDir + '/**/*.scss', ['css']);
gulp.watch(jsDir + '/**/*.js', ['js']);
});
// What tasks does running gulp trigger?
gulp.task('default', ['css', 'js', 'watch']);
This is working fine for my javascript. Also, when I run "gulp" the first time, it compiles all my scss files and moves them accordingly. However, the watch task is not working for my scss files. It DOES work for javascript files. What's really weird (to me) is that when I change my scss source to a specific file, the watch works. So,
gulp.task('css', function () {
return gulp.src(sassDir + '/**/app.scss')
.pipe(sass())
// and the rest is the same
will watch AND compile any changes to my app.scss file, but obviously not to any other scss files.
I have re-arranged and googled all I can. I don't understand why it won't work for watching scss.
EDIT: Strangely, it seems to be notify that is breaking the css watcher. When I comment it out like so:
gulp.task('css', function () {
return gulp.src(sassDir + '/**/*.scss')
.pipe(sass())
.pipe(autoprefix('last 10 version'))
.pipe(gulp.dest(targetCSSDir))
//.pipe(notify('CSS minified'))
});
everything works as expected.
Thanks in advance.

Categories