Problem with gulp iconfonts, what i missing? - javascript

Where is problem? https://i.ibb.co/L0PsxWV/Screenshot-5.png
I have install gulp 3.9.1, and NODE.js 10.13.3...
"use strict";
var iconfont = require('gulp-iconfont');
var runTimestamp = Math.round(Date.now()/1000);
gulp.task('Iconfont', function(){
return gulp.src(['src/icons/*.svg'])
.pipe(iconfont({
fontName: 'myfont', // required
prependUnicode: true, // recommended option
formats: ['ttf', 'eot', 'woff'], // default, 'woff2' and 'svg' are available
timestamp: runTimestamp, // recommended to get consistent builds when watching files
}))
.on('glyphs', function(glyphs, options) {
// CSS templating, e.g.
console.log(glyphs, options);
})
.pipe(gulp.dest('src/fonts/'));
});

add this top of gulpfile.js :
var gulp = require('gulp')

Related

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.

How to include copyright information (from a text file) using gulp?

I have the following task in gulp and I need to ADD at the beginning of my concatenated file (testApp.css) some text for copyright information.
How to achieve it in gulp?
gulp.task('flat', function () {
gulp.src(['themes/**/*.styl', '!themes/**/**mixins**.styl', '!themes/**/**variables**.styl'])
.pipe(stylus({
compress: true,
use: nib()
}))
.pipe(concat('testAll.css'))
.pipe(gulp.dest('testx'));
});
You can use prepend with gulp-insert
npm install gulp-insert
Used in combination with fs:
var fs = require('fs');
var insert = require('gulp-insert');
var copyright = function () {
return fs.readFileSync('copyright.txt');
};
gulp.task('flat', function () {
gulp.src(['themes/**/*.styl', '!themes/**/**mixins**.styl', '!themes/**/**variables**.styl'])
// Your other stuff
.pipe(insert.prepend(copyright));
.pipe(gulp.dest('testx'));
});
Check it out on GitHub for more information.
I was able to solve my issue using gulp-header. Suggestion for other suitable plugins are welcome.
var stylus = require('gulp-stylus');
var nib = require('nib');
var concat = require('gulp-concat');
var header = require('gulp-header');
var fs = require('fs');
gulp.task('flat', function () {
gulp.src(['themes/**/*.styl', '!themes/**/**mixins**.styl', '!themes/**/**variables**.styl'])
.pipe(stylus({
compress: true,
use: nib()
}))
.pipe(concat('testAll.css'))
.pipe(header(fs.readFileSync('copyright.txt', 'utf8')))
.pipe(gulp.dest('test'));
});

Gulp watch not called from within Nodemon

So I have my Gulp file as below.
The 'watch' block seems to work absolutely fine, and do what is expected. Nodemon works in the way that it detects file changes and refreshes the server, that works too.
But I can't for the life of me get Nodemon to call the 'watch' method when a file changes.
On line 81, the .on('start' is called succesfully from nodemon, but the code inside the 'watch' method is never executed.
var gulp = require('gulp');
var gutil = require('gulp-util'); // For logging stats and warnings
var jshint = require('gulp-jshint'); // For checking JavaScript for warnings
var concat = require('gulp-concat'); // For joining together multiple files
var uglify = require('gulp-uglify'); // For minimising files
var coffee = require('gulp-coffee'); // For compiling coffee script into js
var cofLint = require('gulp-coffeelint');// For checking coffee script for errors
var less = require('gulp-less'); // For compiling Less into CSS
var cssLint = require('gulp-csslint'); // For checking the awesomeness of css
var minCss = require('gulp-minify-css');// For minifying css
var uncss = require('gulp-uncss'); // For deleting unused CSS rules
var footer = require('gulp-footer'); // For adding footer text into files
var nodemon = require('gulp-nodemon'); // For the super cool instant refreshing server
var bSync = require('browser-sync'); // Syncs the place between multiple browsers for dev
var es = require('event-stream'); // For working with streams rather than temp dirs
var sourcePath = "sources";
var destPath = "public";
var jsFileName = "all.min.js";
var cssFileName = "all.min.css";
var footerText = "";
/* JavaScript Tasks */
gulp.task('scripts', function(){
var jsSrcPath = sourcePath + '/javascript/**/*';
var jsResPath = destPath + '/javascript';
var jsFromCs = gulp.src(jsSrcPath+'.coffee')// Get all coffee script
.pipe(cofLint()) // Check CS for errors or warnings
.pipe(cofLint.reporter()) // Output the error results
.pipe(coffee()); // Convert coffee to vanilla js
var jsFromPlain = gulp.src(jsSrcPath+'.js');// get all vanilla JavaScript
return es.merge(jsFromCs, jsFromPlain) // Both js from cs and vanilla js
.pipe(jshint()) // Check js errors or warnings
.pipe(jshint.reporter('jshint-stylish')) // Print js errors or warnings
.pipe(concat(jsFileName,{newLine: ';'})) // Concatenate all files together
.pipe(uglify()) // Minify JavaScript
.pipe(footer(footerText)) // Add footer to script
.pipe(gulp.dest(jsResPath)); // Save to destination
});
/* CSS Tasks */
gulp.task('styles', function(){
var cssSrcPath = sourcePath + '/styles/**/*';
var cssResPath = destPath + '/stylesheet';
var cssFromLess = gulp.src(cssSrcPath+'.less') // Get all Less code
.pipe(less()); // Convert Less to CSS
var cssFromVanilla = gulp.src(cssSrcPath+'.css');// Get all CSS
return es.merge(cssFromLess, cssFromVanilla) // Combine both CSS
.pipe(cssLint()) // Check CSS for errors or warnings
.pipe(cssLint.reporter()) // And output the results
.pipe(concat(cssFileName)) // Concatenate all files together
.pipe(minCss({compatibility: 'ie8'})) // Minify the CSS
.pipe(gulp.dest(cssResPath)); // Save to destination
});
/* Configure files to watch for changes */
gulp.task('watch', function() {
gulp.watch(sourcePath+'/**/*.{js,coffee}', ['scripts']);
gulp.watch(sourcePath+'/**/*.{css,less}', ['styles']);
});
/* Start Nodemon */
gulp.task('demon', function () {
nodemon({
script: './bin/www',
ext: 'js coffee css less html',
env: { 'NODE_ENV': 'development'}
})
.on('start', ['watch'])//TODO: ERROR: watch is never called, even though start is called
.on('change', ['watch'])
.on('restart', function () {
console.log('restarted!');
});
});
/* Default Task */
gulp.task('default', ['demon']);
Any suggestions why this may be happening?
Is there something wrong with my Gulp file?
(and yes, I know the code is a little over-commented, I work with apprentices and they like English better than code ;)
The problem is that Nodemon and browser-sync both need to be running. This code works:
gulp.task('nodemon', function (cb) {
var called = false;
return nodemon({
script: './bin/www',
watch: ['source/**/*']
})
.on('start', function onStart() {
if (!called) { cb(); }
called = true;
})
.on('restart', function onRestart() {
setTimeout(function reload() {
bSync.reload({
stream: false
});
}, 500);
});
});
gulp.task('browser-sync', ['nodemon', 'scripts', 'styles'], function () {
bSync.init({
files: ['sources/**/*.*'],
proxy: 'http://localhost:3000',
port: 4000,
browser: ['google chrome']
});
gulp.watch(sourcePath+'/**/*.{js,coffee}', ['scripts']);
gulp.watch(sourcePath+'/**/*.{css,less}', ['styles']);
gulp.watch("sources/**/*").on('change', bSync.reload);
gulp.watch("views/**/*.jade").on('change', bSync.reload);
});
/* Default Task */
gulp.task('default', ['clean', 'browser-sync']);

Set working directory in gulpfile.js?

Is there a way to set the working directory for Gulp within a gulpfile, so that I can run a gulp command from a subdirectory without running into any issues? I ran a search for this and didn't find what I was looking for.
To clarify, I'm aware of adding a prefix to the files I'm using. However, instead of this -
var gulp = require('gulp');
var jshint = require('gulp-jshint');
...
var paths = {
js: [__dirname + 'app/*/*.js', __dirname + '!app/lib/**'],
css: __dirname + 'app/*/*.styl',
img: __dirname + 'app/img/*',
index: __dirname + '*.html',
dist: __dirname + 'dist'
};
I'd like to do something like this:
var gulp = require('gulp');
var jshint = require('gulp-jshint');
...
gulp.cwd(__dirname); // This would be much easier to understand, and would make future edits a bit safer.
var paths = {
js: ['app/*/*.js', '!app/lib/**'],
css: 'app/*/*.styl',
img: 'app/img/*',
index: '*.html',
dist: 'dist'
};
I'm wondering if Gulp exposes this functionality. Perhaps node itself allows this.
(I realize that there is likely a way to do command line itself when I run the command, but I would like to include it in the gulp file, especially for distribution purposes. I want the working directory for gulp to match the directory in which the gulpfile resides.)
Thanks!
Besides option.cwd, you can also use process.chdir(yourDir)
it could be used anywhere in a gulpfile. e.g.
process.chdir(yourDir);
var gulp = require('gulp');
Make sure your gulp is up-to-date( > 3.8.10), this may not work in older gulp.
Instead of concatenating strings by yourself, you should be using path.join since it will take care of the proper slash, and following that path you can add a shorcut:
var path = require('path'),
p = function () {
Array
.prototype
.unshift
.call(arguments, __dirname);
return path.join.apply(path, arguments);
};
console.log(p('a', 'b', 'c'));
Or, well, you can just:
gulp.src(..., {cwd: __dirname})
gulp.dest(..., {cwd: __dirname})
Something like:
var src = function (globs, options) {
options = options || {};
options.cwd = __dirname;
return gulp.src(globs, options);
};
var dest = function (folder, options) {
options = options || {};
options.cwd = __dirname;
return gulp.dest(folder, options);
};
Look here and here.

Browserify + gulp becoming slow

We've been using gulp and browserify to create builds of our project whenever a js file changes. As the project has grown this process has become incredibly slow, from 200ms -> ~5s. The project has 69 directories, 173 files, and a max depth of 4 folders. We are applying a few transforms. Here's our build code.
var buildJS = function (entryPoint, name, cb) {
var browserify = require('browserify');
var uglify = require('gulp-uglify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var reactify = require('reactify');
var literalify = require('literalify');
var brfs = require('brfs');
browserify()
.require(entryPoint + '/' + name + '.jsx')
.transform({
global: true
}, reactify)
.transform({
global: true
}, brfs)
.transform({
global: true
}, literalify.configure(literalifyConfig))
.external(config.libs)
.bundle({
debug: config.DEV,
//detectGlobals : false
})
.on('error', handleError)
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(gulpIf(!config.DEV, uglify()))
.pipe(gulp.dest(config.buildPath + '/' + name))
.on('finish', cb)
};
Is this just normal behavior based on our project size? Or are we doing something wrong?
That's because browserify always recompile everything. You should be using incremental builds instead if you want good perfs.
I've developed a gulp plugin precisely for that: https://github.com/ngryman/gulp-bro.

Categories