running Gulp gives throw er; // Unhandled 'error' event - javascript

main.js
var React = require('react');
var App = require('./components/app.js');
React.render(
<App />,
document.getElementById('container')
);
app.js
var React = require('react');
var App = React.createClass({
render: function(){
return (
<p>Hello</p>
);
}
});
module.exports = App;
is there any problem in gulpfile.js? because it works fine if i write react component code inside main.js file.

You're forgetting to transform your JSX into Javascript.
Here's my gulp build task - It uses browserify and reactify to transform and bundle my components, then minifies them, and finishes by placing them into a directory that my application reads from.
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var reactify = require('reactify');
var streamify = require('gulp-streamify');
gulp.task('build', function () {
browserify({
entries : ['./js_modules/main.js'],
transform : [reactify],
})
.bundle()
.pipe(source('bundle.js'))
.pipe(streamify(uglify('bundle.js')))
.pipe(gulp.dest('src/main/webapp/js/bundle.js'));
});

Related

How to install gulp-sass-glob

When I am trying to save scss files which are imported to main sccs file - every time I need resave main scss file to apply changes. therefore I have decided to install gulp-sass-glob according to this https://www.npmjs.com/package/gulp-sass-glob
but unfortunately it does not work.
Here is my code, please help me how to integrate gulp-sass-glob in my gulp file or what is wrong here. Thank you.
const { src, dest, parallel, series, watch } = require('gulp');
// Load plugins
const sass = require('gulp-sass');
const browsersync = require('browser-sync').create();
const htmlmin = require('gulp-htmlmin');
// Directories
const SRC = './src/';
const DEST = './dist/';
const DEST_CSS = `${DEST}css/`;
const SRC_CSS = `${SRC}scss/*main.scss`;
var gulp = require('gulp');
var sassGlob = require('gulp-sass-glob');
gulp.task('styles', function () {
return gulp
.src(SRC_CSS)
.pipe(sassGlob())
.pipe(sass())
.pipe(gulp.dest(DEST_CSS));
});
// Watch files
function watchFiles() {
watch(`${SRC_CSS}*`, css);
watch(`${SRC}lang`, html);
}
// BrowserSync
function browserSync() {
browsersync.init({
server: {
baseDir: DEST
},
port: PORT
});
}
// Tasks to define the execution of the functions simultaneously or in series
exports.watch = series(
clear,
parallel( css, html, copyStaticHTML, watchFiles, browserSync)
);
exports.default = series(clear, parallel(js, css, html, copyStaticHTML));

Forward reference tasks not defined before use

I am using multiple files with gulp#4 where the main gulpfile.js includes all other files within the ./tasks/ directory. We are using the npm gulp-hub package to include multiple gulpfiles with the ./tasks/ directory. However we are getting the following error message when calling the tasks.
Forward referenced tasks 'clean-minify-js` not defined before use
How can we include multiple gulpfiles within the main gulpfile.js so that we can call tasks?
Current gulpfile.js:
'use strict';
var gulp = require('gulp'),
HubRegistry = require('gulp-hub');
var genericHub = new HubRegistry('./tasks/scripts.js');
gulp.registry(genericHub);
var watchers = function(done) {
gulp.watch('src/*.js', gulp.parallel('clean-minify-js'));
done();
}
gulp.task('watch', gulp.series(watchers));
Current ./tasks/scripts.js
'use strict';
var gulp = require('gulp'),
clean = require('gulp-clean'),
uglify = require('gulp-uglify');
gulp.task('clean-scripts', function() {
return gulp.src(dest.js)
.pipe(clean({read:false, force: true});
});
gulp.task('minify-js', gulp.series('clean-scripts', function() {
gulp.src(src.js)
.pipe(uglify())
.pipe(gulp.dest(dest.js));
}));
gulp.task('clean-minify-js', gulp.series('minify-js'));
Folder structure:
some/path/gulpfile.js
some/path/tasks/scripts.js
To resolve the issue, I had to do the following.
Use the require-dir package to include all files within the ./tasks/ directory.
convert tasks that were designed for gulp#3.9.1 into functions for gulp#4
use gulp.series to set the functions to run in the particular order we needed
gulpfile.js
'use strict';
var gulp = require('gulp'),
requireDir = require('require-dir');
requireDir('./tasks/');
var watchers = function(done) {
gulp.watch('src/*.js', gulp.parallel('clean-minify-js'));
done();
}
gulp.task('watch', gulp.series(watchers));
./tasks/scripts.js
'use strict';
var gulp = require('gulp'),
clean = require('gulp-clean'),
uglify = require('gulp-uglify');
function cleanScripts() {
return gulp.src(dest.js)
.pipe(clean({read:false, force: true});
}
function minJs() {
return gulp.src(src.js)
.pipe(uglify())
.pipe(gulp.dest(dest.js));
}
gulp.task('clean-minify-js', gulp.series(cleanScripts, minJs));

Browserify: Exported function not found after bundling Bootstrap

I'm using Browserify to create a bundle which contains an exported function that I want to call within a <script> tag. Everything works fine until I require Bootstrap, at which point the function is no longer accessible and I get the error:
TypeError: mainBundle.greeting is not a function
Here's the code:
JavaScript (main.js):
window.jQuery = require('jquery');
window.$ = global.jQuery;
module.exports = {
greeting
};
function greeting (name) {
return `Hello ${name}!`;
}
HTML
<script src="js/bundle.js"></script>
<script>
// Update greeting
$('#greeting').text(mainBundle.greeting('Foo'));
</script>
Gulpfile:
Taken pretty much from the Gulp Browserify recipe. You can see I've added the standalone option to customOpts to generate a standalone module as well as require to add Bootstrap. The issue occurs when the require line is commented in.
const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const concat = require('gulp-concat');
const watchify = require('watchify');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const log = require('gulplog');
// add custom browserify options here
const customOpts = {
entries: ['./src/js/main.js'],
// require: ['bootstrap', 'jquery'], // UNCOMMENT CAUSES ISSUE
standalone: 'mainBundle',
debug: true
};
const opts = {...watchify.args, ...customOpts};
const b = watchify(browserify(opts));
console.log('Browserify options: ', opts);
// add transformations here
// i.e. b.transform(coffeeify);
exports.js = bundle; // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', log.info); // output build logs to terminal
function bundle() {
return b.bundle()
// log errors if they happen
.on('error', log.error.bind(log, 'Browserify Error'))
.pipe(source('bundle.js'))
// optional, remove if you don't need to buffer file contents
.pipe(buffer())
// optional, remove if you dont want sourcemaps
.pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
// Add transformation tasks to the pipeline here.
.pipe(sourcemaps.write('./')) // writes .map file
.pipe(gulp.dest('./dist/js'));
}
Hmm, putting the require in main.js resolves the issue:
const bootstrap = require('bootstrap');
window.jQuery = require('jquery');
window.$ = global.jQuery;
module.exports = {
greeting
};
function greeting (name) {
return `Hello ${name}!`;
}
If anyone has a better answer that would allow me to use the Browserify require option, I will happily accept your answer. I would prefer to use the config option to avoid importing things that are not explicitly required in my scripts.

How I can findElement in DOM with Gulp? Its for testing an Electron App

I'm using this code:
'use strict';
var gulp = require('gulp'),
childProcess = require('child_process'),
electron = require('electron-prebuilt');
var Application = require('spectron').Application;
var assert = require('assert');
gulp.task('run', function () {
childProcess.spawn(electron, ['./app/main.js'], { stdio: 'inherit' });
var title=window.document.getElementsByTagName('title');
console.log('title');
});
After that I'm running - gulp run
but I get the following error message:
Reference Error: window is not defined at Gulp.

Cannot find variable on client side react code

After some research on the benefits of the isomorphic/universal javascript apps and server side rendering I have decided to use it in a project.
I am using Express.js and React.js to achieve server side and client side rendering.
One problem I have faced recently is my browser javascript cannot find a React variable which is a React component. It gives the error message of well known ReferenceError: Can't find variable: QuestionBox.
This react component is defined in the questionbox.js and this file used for server side after transpiled by babel in node.js and for client side rendering after browserifyed and rectifyed in a gulp task.
What can be the point here I am missing? It can be the gulp generated transformed file that is loaded by the browser by a script tag. The full code is in this gist.
questionbox.js:
var React = require('react');
var marked = require('marked');
/*
-QuestionBox
-QuestionList
-Question
*/
var Question = React.createClass({//Omitted here for simplicity: https://gist.github.com/isikfsc/b19ccb5e396fd57693d2f5b876ea20a0});
var QuestionList = React.createClass({//Omitted here for simplicity: https://gist.github.com/isikfsc/b19ccb5e396fd57693d2f5b876ea20a0});
var QuestionBox = React.createClass({
loadQuestionsFromServer: function() {
return true;
},
getInitialState: function() {
return {data: []};
},
componentWillMount: function() {
this.loadQuestionsFromServer();
setInterval(this.loadQuestionsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="questionBox">
<h1>Questions</h1>
<QuestionList data={this.state.data} />
</div>
);
}
});
module.exports.QuestionBox = QuestionBox;
gulpfile.js:
var gulp = require('gulp');
var browserify = require('browserify');
var watchify = require('watchify');
var source = require('vinyl-source-stream');
var reactify = require('reactify');
var production = process.env.NODE_ENV === 'production';
function scripts(watch) {
var bundler, rebundle;
bundler = browserify('src/components/questionbox.js', {
basedir: __dirname,
debug: !production,
cache: {}, // required for watchify
packageCache: {}, // required for watchify
fullPaths: watch // required to be true only for watchify
});
if(watch) {
bundler = watchify(bundler)
}
bundler.transform(reactify);
rebundle = function() {
var stream = bundler.bundle();
//stream.on('error', handleError('Browserify'));
stream = stream.pipe(source('bundle.js'));
return stream.pipe(gulp.dest('./dist/components'));
};
bundler.on('update', rebundle);
return rebundle();
}
gulp.task('watchScripts', function() {
gulp.watch('./src/components/*.js', ['scripts']);
});
gulp.task('scripts', function() {
return scripts(false);
});
gulp.task('watchScripts', function() {
return scripts(true);
});
I believe the problem is that the component is not (and really should not be) exposed to the global scope.
All the code inside the browserify bundle in not accessible from outside. So what should be done next is moving render function into the bundle.
To begin with, you can create new file (say, entry.js) and set it as an entry point for browserify in gulpfile.js:
bundler = browserify('src/entry.js', {
Then, You could move JavaScript from the template (.ejs) to this entry point.
var ReactDOM = require('react-dom');
var QuestionBox = require('./components/questionbox.js').QuestionBox;
ReactDOM.render(QuestionBox({}), document.getElementById('mount-node'));
As long as browserify bundle is only used by the client, You don't have to change anything on the server.

Categories