How do I use gulp to convert all jsx files to JavaScript?
When I try to do so, I get the error undefined function require
I'm using the following script.
What I want to do is use gulp to convert all jsx to JavaScript. Also use browserfy in my jsx files.
var gulp = require('gulp')
var react = require('gulp-react')
gulp.task('transpile-js', function() {
return gulp.src('./src/*.jsx')
.pipe(react({harmony: true}))
.pipe(gulp.dest('./build'))
})
I have jsx files in the src directory. I want to convert them into one JavaScript file and store the result in the build directory
Take a look at my domno repo for more:
var gulp = require('gulp'),
uglify = require('gulp-uglify'),
browserify = require('browserify'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer');
gulp.task('script', function () {
return browserify({
entries : ['the/path/to/the/main/entry/file.js'],
transform: ['babelify']
})
.bundle()
.pipe(source('app.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest(dir.web));
});
There are several ways of configuring Browserify...
Related
The code bellow doesn't merge correctly rev-manifest.json file.
I loop several JS tasks and just one is merged, although hash files are being created and stored correctly.
I already tried a ton of things, I checked gulp-rev and some users seam to have similar problems. Some of them are creating several manifest files and proceed with the actual merge at the end. I would like to discard this solutions since it's slow and ugly.
If I comment the concat(...) line the manifest file registers all the JS tasks.
Is this a BUG or am I missing something here?
gulp 3.9.1
gulp-concat 2.6.0
gulp-rev 7.0.0
var gulp = require('gulp');
var less = require('gulp-less');
var minifycss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var rev = require('gulp-rev');
var jsFiles = {
task1: [
'./path/file1.js'
],
task2: [
'./path/file2.js',
'./path/file2.js'
]
};
function jsTask(key) {
gulp.task(key, function() {
gulp.src(jsFiles[key])
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(uglify())
// IT WORKS WHEN I COMMENT THIS LINE
.pipe(concat(key + '.min.js'))
.pipe(rev())
.pipe(gulp.dest('./public/js'))
.pipe(rev.manifest({merge:true }))
.pipe(gulp.dest('.'));
});
}
gulp.task('less', function() {
return gulp.src(['./path/less/*.less'])
.pipe(less({errLogToConsole: true}))
.pipe(minifycss())
.pipe(rev())
.pipe(gulp.dest('./path/public/css'))
.pipe(rev.manifest({merge:true }))
.pipe(gulp.dest('.'));
});
for (var key in jsFiles) {
jsTask(key);
}
var defaultTasks = ['less'];
for (var key in jsFiles) {
defaultTasks.push(key);
}
gulp.task('default', defaultTasks);
You can pass the name of the manifest file you want to create(different for each gulp task) to manifest function of the gulp-rev-all module like below
gulp.task('productionizeCss', function () {
return gulp
.src(['dist/prod/**/*.css'])
.pipe(revAll.revision({
fileNameManifest: 'css-manifest.json'
}))
.pipe(gulp.dest('dist/prod/'))
.pipe(revAll.manifestFile())
.pipe(gulp.dest('dist/prod/'));
});
gulp.task('productionizeJS', function () {
return gulp
.src(['dist/prod/**/*.js'])
.pipe(revAll.revision({
fileNameManifest: 'js-manifest.json'
}))
.pipe(gulp.dest('dist/prod/'))
.pipe(revAll.manifestFile())
.pipe(gulp.dest('dist/prod/'));
});
Here, I have two gulp tasks, one to revise all JS and one for CSS.So, I have created two manifest files css-manifest.json, js-manifest.json.
Then I specified both the manifest files in src of the rev-replace module as shown below:
gulp.task('revReplaceIndexHtml', function () {
var manifest = gulp.src(["dist/prod/js-manifest.json", 'dist/prod/css-manifest.json']);
return gulp.src('dist/dev/referralswebui/index.html')
.pipe(revReplace({ manifest: manifest, replaceInExtensions: ['.html']}))
.pipe(gulp.dest('dist/prod/referralswebui/'));
});
I would suggest using gulp-useref instead of gulp-concat.
Given your setup, I think key references a glob path, or at least I hope so. Otherwise you are trying to concatenate a single file, or no files which may crash the concat plug-in. Emphasis on may.
Also, since you are using gulp-rev, I suggest using gulp-rev-replace which will automatically update your index references to the reved files.
Edit
Sometimes rev.manifest behaves in ways that I would describe as buggy. Just to exhaust all possibilities remove the merge option for the manifest and run concat. Or run concat and remove manifest altogether.
I have a gulpfile.js with a method:
gulp.task('default', function() {...}}
How can I pass data out of gulp so that I can use it in another javascript file?
You can create another module that contains your array and require it in other javascript files:
variables.js
module.exports = {
myArray : ['value1', 'value2']
}
gulpfile.js
var gulp = require('gulp'),
vars = require('./variables');
gulp.task('default', function() {
console.log(vars.myArray);
});
I am using gulp for the very first time.
I managed doing merge streaming for css files but somehow its not working for javascript files.
Here is my code,
gulp.task('styles', () => {
var commonStyles = gulp.src([
'css/website/bootstrap.min.css',
'css/website/font.css'
])
// Concatenate and minify styles
.pipe(minifyCss())
.pipe(concat('style.min.css'))
.pipe(gulp.dest('dist/styles'));
var otherStyles = gulp.src([
'css/website/landing.css',
'css/website/careersNew1.css'
])
.pipe(minifyCss())
.pipe(gulp.dest('dist/styles'));
return merge(commonStyles, otherStyles);
});
// Concatenate and minify JavaScript
gulp.task('scripts', () => {
var commonScript = gulp.src([
'js/scripts/jquery.min.js',
'js/scripts/bootstrap.min.js'
])
.pipe(uglify())
.pipe(concat('style.min.js'))
.pipe(gulp.dest('dist/scripts'));
var otherScript = gulp.src([
'js/bf_scripts.js',
'js/custom_rbox.js'
])
.pipe(uglify())
.pipe(gulp.dest('dist/scripts'));
return merge(commonScript, otherScript);
});
Css output is working fine. But I am not getting any otherScript files in my dist/scripts/ folder
You should only run uglify() on your custom scripts, because the jQuery and Bootstrap versions you're using are already minified/uglified, and that wastes processing time and slows down your build script. Also, I recommend keeping libraries you download in separate folders from the custom code you write. Keep jQuery and Bootstrap in lib folder, and your code in src folder. You can then use wildcard globs to grab all files instead of specifying individual files.
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var addsrc = require('gulp-add-src');
gulp.task('scripts', function() {
// First, uglify custom JS that you wrote
return gulp.src('src/scripts/**/*.js')
.pipe(uglify())
// Now, prepend the already-minfied JS libraries you're importing and concat into style.min.js
.pipe(addsrc.prepend('lib/scripts/**/*.js'))
.pipe(concat('style.min.js'))
.pipe(gulp.dest('dist/scripts'))
})
gulp.task('default', ['scripts'])
try to use buffer before uglify;
var buffer = require('gulp-buffer');
.pipe(buffer())
.pipe(uglify())
I am a newbie to gulp. I am trying to create one single vendor.css file and vendor.js file with gulp.
The vendor.css should be
-bootstrap.css
The vendor.js should be
-jquery.js
-bootstrap.js
-angular.js
-angular-ui-router.js
gulpfile.js
// Include Gulp
var gulp = require('gulp');
// Include plugins
var plugins = require("gulp-load-plugins")({
pattern: ['gulp-*', 'gulp.*'],
replaceString: /\bgulp[\-.]/
});
// Define default destination folder
var dest = 'public';
gulp.task('vendorjs', function(){
var filterJS = plugins.filter('**/*.js');
return gulp.src('./bower.json')
.pipe(plugins.mainBowerFiles( ))
.pipe(filterJS)
.pipe(plugins.concat('vendor.js'))
.pipe(plugins.uglify())
.pipe(filterJS.restore())
.pipe(gulp.dest(dest+"/vendor/js/"));
});
gulp.task('vendorcss', function(){
var filterCSS = plugins.filter('**/*.css');
return gulp.src('./bower.json')
.pipe(plugins.mainBowerFiles( ))
.pipe(filterCSS)
.pipe(plugins.concat('vendor.css'))
.pipe(plugins.uglify())
.pipe(filterCSS.restore())
.pipe(gulp.dest(dest+"/vendor/css/"));
});
gulp.task('default', function() {
// place code for your default task here
});
gulp.task('serve', ['vendorcss','vendorjs'], function () {
});
When i run gulp serve, it executes without error. But I end up with
public/vendor/css/angular/angular.js
public/vendor/css/angular-ui-router/release/angular-ui-router.js
public/vendor/css/bootstrap/dist/js/bootstrap.js
public/vendor/css/bootstrap/less/bootstrap.less
public/vendor/css/jquery/dist/jquery.js
public/vendor/js/vendor.js
public/vendor/js/bootstrap/less/bootstrap.less
Why do my css files are missing. Why do i get less file.
My output should be
public/vendor/vendor.js
public/vendor/vendor.css
How do i map the vendor.js and vendor.css with my html
I'm trying to write a gulp task allowing me to use modules in JS (CommonJS is fine), using browserify + 6to5. I also want source mapping to work.
So:
1. I write modules using ES6 syntax.
2. 6to5 transpiles these modules into CommonJS (or other) syntax.
3. Browserify bundles the modules.
4. Source maps refers back to the original ES6 files.
How to write such a task?
Edit: Here's what I have so far:
gulp task
gulp.task('browserify', function() {
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var to5ify = require('6to5ify');
browserify({
debug: true
})
.transform(to5ify)
.require('./app/webroot/js/modules/main.js', {
entry: true
})
.bundle()
.on('error', function(err) {
console.log('Error: ' + err.message);
})
.pipe(source('bundle.js'))
.pipe(gulp.dest(destJs));
});
modules/A.js
function foo() {
console.log('Hello World');
let x = 10;
console.log('x is', x);
}
export {
foo
};
modules/B.js
import {
foo
}
from './A';
function bar() {
foo();
}
export {
bar
};
modules/main.js
import {
bar
}
from './B';
bar();
The code seems to be working, but it's not minified and the source map is inline (which is not really working for production).
Use this as your start point:
var gulp = require('gulp');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var to5ify = require('6to5ify');
var uglify = require('gulp-uglify');
gulp.task('default', function() {
browserify('./src/index.js', { debug: true })
.transform(to5ify)
.bundle()
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
.pipe(uglify())
.pipe(sourcemaps.write('./')) // writes .map file
.pipe(gulp.dest('./build'));
});
I didn't understand why we had to use certain things in order to get this to work so I'm adding my own answer here. For those looking for a solution with babelify, I added one below. I also thought it'd be good to talk about what each line does.
For those that want to use ES6 in their Gulpfile, you can look here but Gulp supports it if you rename your file to Gulpfile.babel.js as of Gulp 3.9
One big thing to note is you need to use vinyl-source-stream with Browserify in order to convert the output into something Gulp can understand. From there a lot of gulp plugins require vinyl buffers which is why we buffer the source stream.
For those not familiar with sourcemaps, they are essentially a way for you to map your minifed bundled file to the main source file. Chrome and Firefox support it so when you debug you can look at your ES6 code and where it failed.
import gulp from 'gulp';
import uglify from 'gulp-uglify';
import sourcemaps from 'gulp-sourcemaps';
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import browserify from 'browserify';
import babel from 'babelify';
gulp.task('scripts', () => {
let bundler = browserify({
entries: ['./js/main.es6.js'], // main js file and files you wish to bundle
debug: true,
extensions: [' ', 'js', 'jsx']
}).transform(babel.configure({
presets: ["es2015"] //sets the preset to transpile to es2015 (you can also just define a .babelrc instead)
}));
// bundler is simply browserify with all presets set
bundler.bundle()
.on('error', function(err) { console.error(err); this.emit('end'); })
.pipe(source('main.es6.js')) // main source file
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true })) // create sourcemap before running edit commands so we know which file to reference
.pipe(uglify()) //minify file
.pipe(rename("main-min.js")) // rename file
.pipe(sourcemaps.write('./', {sourceRoot: './js'})) // sourcemap gets written and references wherever sourceRoot is specified to be
.pipe(gulp.dest('./build/js'));
});
Other useful readings:
Gulp browserify the gulp-y way