huge files size when browserifying angular - node.js

I am just trying gulp + angular + browserify app and got a huge browserified file, about 2M. While all it does just require angular and a sample controller.
// setup gulp task
gulp.task('browserify', function() {
gulp.src([util.format('%s/app/main.js', JS_BASE_DIR)])
.pipe(browserify({
insertGlobals: true,
debug: true
}))
// Bundle to a single file
.pipe(concat('bundle.js'))
// Output it to our dist folder
.pipe(gulp.dest(util.format('%s/js/', BUILD_BASE_DIR)));
});
//in the main.js
(function() {
'use strict';
var angular = require('angular');
var indexCtrl = require('./controllers/indexCtrl');
var app = angular.module('wohu.app', []);
app.controller('ctrl', indexCtrl);
})();
angular is installed via
npm install angular
The bundle.js is not minified but it shouldn't be that huge. Wonder what the problem is.

Browserify will include a source map in the bottom of the file which can make it seem HUGE. You can strip this out (and you should) for production. You can use exorcist for this (https://www.npmjs.com/package/exorcist) which pulls the source map into an external file for you and can be hooked up to your build process (I use Grunt but will work for Gulp too).

Related

deploy module to remote server that is running node.js

I'm working on my app.js in node.js
-- trying to deploy server-side script.
Many fine node.js modules need a require('something');
I use NPM locally, which works for require, as modules are nicely visible in the local node_modules folder structure. but now I'm ready to upload or bundle to a host. I can't run npm on this hosted server.
const Hapi = require('hapi');
will result in
Error: Cannot find module 'hapi'
because I don't know how to copy/install/bundle/ftp files to my host.
Hapi is just an example. Most anything that has a require will need something on the host.
I used webpack to create a server side bundle.js but just sticking bundle.js under /node_modules doesn't do anything.
Most modules have a complex folder structure underneath --- I'm trying to avoid copying a ton of folders and files under /node_modules. Ideally, I want to combine the modules into a bundle.js and have those modules visible to app.js
but I am open to other ideas.
I have not yet tried using webpack to bundle app.js TOGETHER with the various modules. Have you had luck with that approach?
thanks.
I've tried to upload hapi files a folder-ful at a time, reaching a new require('something') error at every step.
'use strict';
const Hapi = require('hapi'); // <-- how can I deploy hapi on my node.js server?
// Create a server with a host and port
const server=Hapi.server({
host:'localhost',
port:8000
});
// Add the route
server.route({
method:'GET',
path:'/hello',
handler:function(request,h) {
return'hello world';
}
});
// Start the server
async function start() {
try {
await server.start();
}
catch (err) {
console.log(err);
process.exit(1);
}
console.log('Server running at:', server.info.uri);
};
start();
one approach that worked: using webpack to bundle the back end js.
thanks to
https://medium.com/code-oil/webpack-javascript-bundling-for-both-front-end-and-back-
end-b95f1b429810
the aha moment... run webpack to create bundle-back.js then
tie bundle-back.js to my node server
**You start your backend server with ‘bundle-back.js’ using:
node bundle-back.js
In other words, include app.js in the bundle with the modules.

Gulp: Trouble setting browserSync and Watch

I'm learning Gulp and NPM and decided to test myself by using Browser-Sync with a PHP project I'm working on (using XAMPP). I know Browser-Sync doesnt work with PHP files, but I wanted to use it with my .css files (and later on perhaps add Sass).
I installed npm, Gulp, Gulp-watch and Browser Sync to my project's root directory and all seemed fine.
I then created a gulp.js file with the following:
var gulp = require('gulp'),
watch = require('gulp-watch'),
browserSync = require('browser-sync').create();
gulp.task('watch', function() {
browserSync.init({
server: {
baseDir: "./"
}
});
watch('css/*.css', function() {
browserSync.reload();
});
});
However, when I gulp watch a new browser window does open but just shows the Cannot GET / error.
Also, the URL shows http://localhost:3002/ rather than http://localhost:myproejct
I read this may have something to do with my baseDir so tried:
baseDir: ""
baseDir: "./"
baseDir: "../myproject"
Would anyone know what I've done wrong?
You are doing way more than is necessary to do what you want. You can just use browsersync as a proxy layer over the top of your hosted site.
See the following example from the docs
# Proxy a PHP app + serve static files & watch them
$ browser-sync start --proxy 'mylocal.dev' --serveStatic 'public' --files 'public'
I think this is what you will need, run it from the physical root of your site and replace mylocal.dev with your php server address
npm install browser-sync -g
browser-sync start --proxy 'mylocal.dev' --serveStatic 'css' --files 'css/*.css'
Your code works fine for me. Assuming your target HTML file works if opened in the browser manually: One common cause of the Cannot Get/ error is using an index file other than Browsersync's default expectation, index.html. Could that be the problem you're having? If you need a custom index file, you can set the index option:
browserSync.init({
server: {
baseDir: 'mybasedirectorypath',
index: 'notindex.html'
}
});
Fwiw, you can also do this more efficiently, and save yourself the weight of installing gulp-watch (this example adapted and simplified from this Browsersync docs example):
var gulp = require('gulp'),
browserSync = require('browser-sync').create();
gulp.task('watch', function() {
browserSync.init({
server: {
baseDir: './'
}
});
gulp.watch('css/*.css').on('change',browserSync.reload)
});
As for using a custom url, check out https://github.com/BrowserSync/browser-sync/issues/646 which has some solutions.

getting webpack to work on openshift

I'm trying to deploy a basic nodejs app to OpenShift. I'm not sure how to do it with webpack though. Do I build the bundle.js file locally and just deploy that along with the index.html? I tried that by putting the bundle.js file in a /public directory and pointing to that using a relative path in the index.html, but I get bundle.js not found error. (It works when I run it locally.) What step am I missing? Must I not use relative paths in OpenShift? I find the documentation for OpenShift rather complicated. If anybody out there can break this down I'd much appreciate it!
I did miss a step: You need to add the directory in the server.js like so:
self.initializeServer = function() {
self.createRoutes();
self.app = express.createServer();
self.app.configure(function() {
self.app.use('/public', express.static(__dirname+'/public'));
});
// Add handlers for the app (from the routes).
for (var r in self.routes) {
self.app.get(r, self.routes[r]);
}
};

npm/gulp/nodejs : Different files for production

I have a gulp script that concatenate and minify my JavaScript.
With the gulp-html-replace plugin I can replace all my JS dependancies by the concatened file in my index.html.
I end up with a dev version (/dev/index.html), with all the single JS files included (easier for debugging) and a production version,with all JS concatened (/prod/index.html).
For now I have a config flag (in NodeJS) in a config.js file and I do the following :
res.render(((config.build === 'prod') ? './prod' : './dev') + 'myPage')
But I'm not really happy with this solution as it adds a lot of code and it's easy to forget to write this code.
Is there a better solution ?
Does this solution take place in Gulp
(by havign a gulp prod and a gulp dev for example)
Or does it take place in Node (by setting up a virtual directory for example)
I am new to this npm/gulp/node workflow and not sure of what belongs where
The way I like to do it is by maintaining two separate versions for index.html.
index-development.html for dev environment and index-production.html for production environment.
The index-development.html includes all the scripts and css (non minified and concatenated) and index-production.html as minified and concatenated scripts and css links.
I construct index.html from gulp script.
By default the index-development.html will be deployed.
If I specify parameter p to the gulp script, it will deploy index-production.html
No need to update the file path of the file to be served in your express router.
First do
npm install yargs
In gulp, I include
var argv = require('yargs').argv;
Check if parameter p (gulp -p) is passed to the gulp (p for production) with
var isProduction = argv.p;
and then,
if(isProduction){
taskSequence = ['combineControllers','combineServices','productionsIndex','startServer'];
} else{
taskSequence = ['developmentIndex','startServer'];
}
gulp.task('default', taskSequence);
gulp.task('startServer', function(){
exec('npm start', function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
});
gulp.task('productionsIndex', function(done) {
return gulp.src('./www/index-productions.html')
.pipe(concat('index.html'))
.pipe(gulp.dest('./public/'));
});
gulp.task('developmentIndex', function(done) {
return gulp.src('./www/index-development.html')
.pipe(concat('index.html'))
.pipe(gulp.dest('./public/'));
});
This way, your index.html file will be constructed dynamically without having to change of the code in your express and you can serve it like
res.render('index');
if you want to user myPage.html everywhere, just replace index.html and index in the code above with myPage.html and myPage.
EDIT:
To start your application in development environment, simply run gulp
To start your application in production environment, simply run gulp -p
Simple!
in your app initialization process you can set the path of your views.
app.set('views', process.cwd() + ((config.build === 'prod') ? '/prod' : '/dev'));
Now you can call the render function like this:
res.render('myPage');

Unable to get connect-livereload to work with express server in gulp task

I am working off of Yeoman's gulp-webapp generator. I have modified my gulp serve task to use my Express server, rather than the default connect server it ships with. My issue is with Livereload functionality. I am trying to simply port the connect-livereload to work with my Express server rather than having to install new dependencies. It's to my understanding that most connect middleware should work fine with Express, so I am assuming connect livereload is compatible with Express 4.
Here are the contents of the relevant tasks in my gulpfile:
gulp.task('express', function() {
var serveStatic = require('serve-static');
var app = require('./server/app');
app.use(require('connect-livereload')({port: 35729}))
.use(serveStatic('.tmp'));
app.listen(3000);
});
gulp.task('watch', ['express'], function () {
$.livereload.listen();
// watch for changes
gulp.watch([
'app/*.ejs',
'.tmp/styles/**/*.css',
'app/scripts/**/*.js',
'app/images/**/*'
]).on('change', $.livereload.changed);
gulp.watch('app/styles/**/*.css', ['styles']);
gulp.watch('bower.json', ['wiredep']);
});
gulp.task('styles', function () {
return gulp.src('app/styles/main.css')
.pipe($.autoprefixer({browsers: ['last 1 version']}))
.pipe(gulp.dest('.tmp/styles'));
});
gulp.task('serve', ['express', 'watch'], function () {
require('opn')('http://localhost:3000');
});
With this simple setup, when I run gulp serve in my cmd everything spins up fine and I can accept requests at http://localhost:3000.
Now if I go and change the body's background color from #fafafa to #f00 in main.css and hit save, my gulp output will respond with main.css was reloaded, as seen in the bottom of this screenshot.
However, my webpage does not update. The background color is still light-grey instead of red.
Is there perhaps a conflict between my express server config and the way gulp handles its files? Is my Express server forcing the use of app/styles/main.css rather than the use of .tmp/styles/main.css? Shouldn't the livereload script handle the injection of the new temporary file?
Thanks for any help.
EDIT:
I was able to move forward a bit by adding livereload.js to the script block of my index file, like so:
<script src="http://localhost:35729/livereload.js"></script>
I am now able to get live changes pushed to the client. Why was this file not getting injected before? How can I ensure this is getting used programatically as opposed to pasting it into my files?
I was able to get past this issue by removing the app.use(require('connect-livereload')({port: 35729})) from my gulpfile, along with a couple of other lines, and having that instantiate in my Express server's app.js file.
My gulpfile's express task now looks like this:
gulp.task('express', function() {
var app = require('./server/app');
app.listen(3000);
});
I added in the connect-livereload just above where I specify my static directory in Express:
if (app.get('env') === 'development') {
app.use(require('connect-livereload')());
}
app.use(express.static(path.join(__dirname, '../app')));
Once I started using this setup, I was getting the livereload.js script injected into my document, and client-side changes are now auto-refreshed just how I wanted.
Hope this helps someone!

Resources