How to avoid bundling ReactJs multiple times using Gulp? - javascript

I am trying to use ReactJS as view library rendering on client-side. Also I am imports lots of components from Material-UI as components.
One issue is that I need to use gulp to setup browserify(for using module in browser ) and babelify(compiling JSX to Javascript). But I found that if React is bundled more than one time, the UI would have error on behavior and styling.
According to this article, I setup the gulpfile.js as the following.
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var gutil = require('gulp-util');
var babelify = require('babelify');
var dependencies = [
'react',
'react-dom',
'material-ui',
'react-tap-event-plugin'
];
var scriptsCount = 0;
gulp.task('scripts', function () {
bundleApp(false);
});
gulp.task('deploy', function (){
bundleApp(true);
});
gulp.task('watch', function () {
gulp.watch(['./app/*.js'], ['scripts']);
});
gulp.task('default', ['scripts','watch']);
function bundleApp(isProduction) {
scriptsCount++;
var appBundler = browserify({
entries: './app/app.js',
debug: true
})
if (!isProduction && scriptsCount === 1){
browserify({
require: dependencies,
debug: true
})
.bundle()
.on('error', gutil.log)
.pipe(source('vendors.js'))
.pipe(gulp.dest('./web/js/'));
}
if (!isProduction){
dependencies.forEach(function(dep){
appBundler.external(dep);
})
}
appBundler
.transform("babelify", {presets: ["es2015", "react"]})
.bundle()
.on('error',gutil.log)
.pipe(source('bundle.js'))
.pipe(gulp.dest('./web/js/'));
}
If I run:
gulp scripts
more than once, the UI would have some problems and error in console.
So HOW should I modify the gulpfile to avoid bundling the React? Help please.

You need to include react-addons-transition-group to your external dependency list. I was facing the same problem.
Here is what I did to resolve it.
Cleaned up node_modules rm -rf node_modules
npm install react-addons-transition-group --save
npm install
Run gulp scripts
I hope that helps.

Related

Gulp compile command isn't compiling the SRC folder from TS to JS in DIst folder

I'm using Gulp to compile my type script into java script. When I initiate the Gulp command it will compile everything in my src folder and puts the compiles files in dist folder which are is Java script now but i only see only one file present in dist folder after compilation i.e. config.json where i am expecting all the files in src to be present in dist after compilation. I am using gulp compile command to compile my files in SRC.
Kindly scroll down the code below to see the folder structure as well.
Thank you.
Here's my gulpfile.js
var gulp = require('gulp');
var ts = require('gulp-typescript');
var zip = require('gulp-zip');
var del = require('del');
var install = require('gulp-install');
var runSequence = require('run-sequence');
var awsLambda = require("node-aws-lambda");
var sourcemaps = require('gulp-sourcemaps');
var gulpMocha = require('gulp-mocha');
var gutil = require('gulp-util');
const babel = require('gulp-babel');
gulp.task('clean', function () {
return del(['./dist','./testJs', './dist.zip']);
});
gulp.task('compile', function () {
return gulp.src(['src/**/*.ts' ]) //'typings/**/*.d.ts'])
.pipe(sourcemaps.init())
.pipe(ts({
noImplicitAny: false,
removeComments: true,
preserveConstEnums: true,
target: 'es2015',
module: 'commonjs',
noExternalResolve: true,
exclude: ["node_modules", "dist"]
}))
.pipe(babel({
presets: [ 'es2015' ],
plugins: ['transform-runtime']
}))
// sourceRoot must be relative to the running directory
// It appears VSCode does resolve the path relative to the cwd
// so using something like /src doesn't work, it has to be relative
// to the /dist folder where we will run the app from
// Need to test if maps help when errors are thrown in aws and if we should upload them
.pipe(sourcemaps.write('.', { sourceRoot: '../src' }))
.pipe(gulp.dest('./dist'))
,
gulp.src(['src/**/*.json'])
.pipe(gulp.dest('./dist'));
});
gulp.task('deploy', function (callback) {
return runSequence(
'clean',
'compile',
'compiletest',
'test',
'node-mods',
callback
);
});```
**Folder structure before running gulp compile**
|
|_ [src folder]
|_CC_ToMRDR
|_Central Repository
app.ts
config.json
test.ts
|_ [other folder's and files like node modules,package.json,tsconfig.json etc]
**Folder structure after running gulp compile**
|
|_ [src folder]
|_CC_ToMRDR
|_Central Repository
app.ts
config.json
test.ts
|
|_ [dist folder]
config.json
|_ [other folder's and files like node modules,package.json,tsconfig.json etc]
Try changing the first gulp.src like this:
return gulp.src('src/**/*.ts')
and the second
.pipe(gulp.src('src/**/*.json'))
Comma breaks the compilation. The second gulp.src must be added as a pipe or it overwrites the first (cfr. https://gulpjs.com/docs/en/getting-started/working-with-files/).
More in depth:
gulp.task('compile', function() {
return gulp.src('src/**/*.ts')
// some coding here
.pipe(gulp.dest('./dist'))
.pipe(gulp.src('src/**/*.json'))
.pipe(gulp.dest('./dist'));
});
Sorry for the edits, but you’re using an older Gulp.js syntax and I was a bit confused.

Generate a local HTML file with PUG (npm / gulp)

How to create a HTML file with the same name as my pug file each time I save using gulp?
All the docs on https://pugjs.org/ explain how to return pug in console...
You need task runner or module bundler for that. So choose one -grunt/gulp/webpack. Consider webpack as newest one and width best functionality.
Here an example width gulp as moust easy to understand from my point of view.
First install npm packages for compiling pug and watch for changes - npm install --save gulp-pug gulp-watch.
Then create and config your gulpfile.js.
First import an npm modules
var pug = require('gulp-pug');
var watch = require('gulp-watch');
Then create compiling task
gulp.task('pug',function() {
return gulp.src('PATH_TO_TEMPLATES/*.jade')
.pipe(pug({
doctype: 'html',
pretty: false
}))
.pipe(gulp.dest('./src/main/webapp/'));
});
And then create watcher
gulp.task('watch', function () {
return watch('PATH_TO_TEMPLATES/*.jade', { ignoreInitial: false })
.pipe(gulp.dest('pug'));
});
And run gulp-watch from you console.
Here an example width gulp 4.0
install npm packages for compiling pug/jade by following command
npm install --save gulp-pug .
create script with name gulpfile.js
//gulpfile.js
var gulp = require("gulp"), pug = require('gulp-pug');
function pugToHtml(){
return gulp.src('src')
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest('dest'));
}
exports.pugToHtml = pugToHtml;
We can run the above code using the following command in your file directory:
gulp pugToHtml
You can now do the same without requiring gulp-watch as well.
Require module:
var pug = require('gulp-pug');
Task example:
//create task
gulp.task('pug', function buildHTML(){
gulp.src('src/pre/*.pug')
.pipe(pug())
.pipe(gulp.dest('src/post'));
});
Watch:
//pug serve
gulp.task('watch', ['pug'], function() {
gulp.watch(['src/pug-pre/*.pug'], ['pug']);
});
You can then run gulp watch. You can also set watch to the default task so you only have to write gulp in Terminal, if you are not automating anything else:
// default task
gulp.task('default', ['watch']);

Gulp Browsersync task not reloading on file changes with new file structure

After changing my project to be organized into src/ and dist/ folders, my changes aren't being compiled and my browsersync task is no longer reloading the page. If I change the color of a div for instance, the color is not updated even if I stop and restart the gulp task. So my question is, how do I change my gulp tasks to watch for changes in the new file structure I am using, and how do I trigger the reload task once the watch task recognizes a change to a file? I think the reload task works, on a previous working version of this gulpfile gulp.watch was working so it doesn't appear to be a problem with that. I tried changing gulp.watch to browserSync.watch as per this answer but that didn't fix it.
I'm guessing this is a problem with my watch task or the browsersync.init but I'm totally stumped.
To be clear, I am making a static webpage using Jade, Bourbon Neat, SCSS, Gulp, and Browsersync.
Here's a link to the full GitHub repo for this project if that helps!
This is my current file structure:
/
dist/
css/
js/
index.html
node_modules/
src/
jade/
js/
scss/
.gitignore
gulpfile.js
package.json
And this is my gulpfile.js:
// VARIABLES
var gulp = require('gulp');
var jade = require('gulp-jade');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var cssmin = require('gulp-cssmin');
var neat = require('node-neat').includePaths;
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
// TASKS
// Jade task
gulp.task('jade', function() {
return gulp.src('src/jade/**/*.jade')
.pipe(jade({ pretty: true }))
.pipe(gulp.dest('dist/'))
});
// SCSS task
gulp.task('scss', function() {
return gulp.src('src/scss/**/*.scss')
.pipe(sass({ style: 'compressed',
noCache: true,
includePaths: neat }))
.pipe(autoprefixer())
.pipe(cssmin())
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('dist/css'))
});
// JS task
gulp.task('js', function() {
return gulp.src('src/js/**/*.js')
.pipe(uglify())
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('dist/js/'))
});
// Watch files for changes
gulp.task('watch', ['browser-sync'], function() {
gulp.watch('dist/**/*.html', reload);
gulp.watch('src/scss/**/*.scss', ['scss', reload]);
gulp.watch('src/**/*.jade', ['jade']);
gulp.watch('src/**/*.js', ['js']);
});
// Start Browsersync server
gulp.task('browser-sync', function() {
browserSync.init(['dist/css/**/*.css', 'dist/js/**/*.js'], {
server: {
baseDir: "dist/"
}
});
});
// Default task
gulp.task('default', ['scss', 'jade', 'js', 'watch', 'browser-sync']);
I have pulled your repo and made some fixes, will push under the "fixes" branch. Few things:
Your index.html was referencing your unminified css, while you only exporting minified.
the watch list needed the subfolders prefxied, so gulp.watch('src/js/**/*.js', ['js']); and not gulp.watch('src/**/*.js', ['js']);
Your browserSync.init was referencing the wrong directories (src and not dist).
What worked for me was to switch gulp.watch to browserSync.watch. BrowserSync's documentation indicates that this feature requires at least version 2.6.0. So you may need to update your version of BrowserSync if you are not using that version.

How to use gulp to minify all the js of angular

So I have installed gulp in my angular project, this is my gulpfile.js at the moment:
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var templates = require('gulp-angular-templatecache');
var minifyHTML = require('gulp-minify-html');
// Minify and templateCache your Angular Templates
// Add a 'templates' module dependency to your app:
// var app = angular.module('appname', [ ... , 'templates']);
gulp.task('templates', function () {
gulp.src([
'./**/*.html',
'!./node_modules/**'
])
.pipe(minifyHTML({
quotes: true
}))
.pipe(templates('templates.js'))
.pipe(gulp.dest('tmp'));
});
// Concat and uglify all your JavaScript
gulp.task('default', ['templates'], function() {
gulp.src([
'./**/*.js',
'!./public/js/**/*.js',
'!./node_modules/**',
'!./gulpfile.js',
'!./dist/all.js'
])
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
When I run gulp default, everything succeeds. But how can I notice this exactly? I don't get the feeling that anything has changed, my js files still look the same.
This is my project structure:
As your gulp configuration specifies, you would have obtained a file named all.js inside your dist/ directory. This is the file that would contain your all *.js files minified code.
You should be including this inside your index.html
Your original js files are untouched. There is template.js under "tmp" folder and all.js under "dist" folder. Those files are minimized.
you can use
gulp build
that will give you a minified js inside a dist.zip
more info click here

Gulp with browserify, tsify, and reactify?

I'm using gulp with browserify and tsify in a TypeScript project. The following is an extract from my gulpfile.js:
var browserified = function (filename, debug) {
var b = browserify({
entries: filename,
debug: debug || false
});
b.plugin('tsify', {
noImplicitAny: true,
target: 'ES5'
});
b.transform('debowerify');
return b.bundle();
};
gulp.task('rebuild', ['lint', 'less'], function() {
var b = browserified ('./src/ts/main.ts', true);
return buildSourceMaps (b);
});
This works so far. I want to extend this so I can require React JSX files. First I tried (from one of my TypeScript files):
import Test = require ('../jsx/Test.jsx');
This doesn't work, though, because tsify would complain as it looks for a TypeScript file ../jsx/Test.jsx.ts. So I use the following hack:
declare var require: any;
var Test = require ('../jsx/Test.jsx');
If Test.jsx is plain vanilla JavaScript, this works. If Test.jsx contains TypeScript, it would fail, which is what I expect. So far, so clear.
Now I want to add reactify to my gulp tasks so I can use JSX in these files. Here I am stuck! I tried adding the following to the function browserified in my gulpfile.js:
b.plugin ('reactify', {
extension: 'jsx'
});
I still get the following error when I call gulp rebuild when Test.jsx contains actual JSX:
Unexpected token <
Obviously, gulp chokes on the first JSX-specific term. I think gulp is trying to pass the JSX through the TypeScript compiler. Which isn't a surprise, since I can't think of a way how to tell tsify to ignore my .jsx files. I'm new to gulp, so I am a bit at a loss. Any ideas how to set up gulp to allow for TypeScript with all .ts files and JSX with all .jsx files?
This is the gulp task I use for development. It uses watchify along with browserify and reactify to build your code, provide source mapping, and rebundle any changes you make on the fly. The path.ENTRY_POINT variable is the main component for your react app (often app.js or main.js).
gulp.task('watch', function() {
gulp.watch(path.HTML, ['copy']);
var watcher = watchify(browserify({
entries: [path.ENTRY_POINT],
transform: [reactify],
debug: true,
cache: {}, packageCache: {}, fullPaths: true
}));
return watcher.on('update', function () {
watcher.bundle()
.pipe(source(path.OUT))
.pipe(gulp.dest(path.DEST_SRC))
console.log('Updated');
})
.bundle()
.pipe(source(path.OUT))
.pipe(gulp.dest(path.DEST_SRC));
});
I used this tutorial to set up my gulpfile.js and it provides a good explanation for every gulp task:
http://tylermcginnis.com/reactjs-tutorial-pt-2-building-react-applications-with-gulp-and-browserify/

Categories

Resources