How can I start the angular app with this gulp script? - angularjs

I took a gulpfile from this location https://github.com/meanjs/mean. My version looks like this, I used a slightly moderated version just to run a dev version:
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
fs = require('fs'),
defaultAssets = require('./config/default'),
glob = require('glob'),
gulp = require('gulp'),
gulpLoadPlugins = require('gulp-load-plugins'),
runSequence = require('run-sequence'),
plugins = gulpLoadPlugins({
rename: {
'gulp-angular-templatecache': 'templateCache'
}
}),
path = require('path'),
endOfLine = require('os').EOL;
// Local settings
var changedTestFiles = [];
// Set NODE_ENV to 'development'
gulp.task('env:dev', function () {
process.env.NODE_ENV = 'development';
});
// Nodemon task
gulp.task('nodemon', function () {
return plugins.nodemon({
script: 'server.js',
nodeArgs: ['--debug'],
ext: 'js,html',
watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
});
});
// Watch Files For Changes
gulp.task('watch', function () {
// Start livereload
plugins.livereload.listen();
// Add watch rules
gulp.watch(defaultAssets.server.views).on('change', plugins.livereload.changed);
gulp.watch(defaultAssets.server.allJS, ['eslint']).on('change', plugins.livereload.changed);
gulp.watch(defaultAssets.client.js, ['eslint']).on('change', plugins.livereload.changed);
gulp.watch(defaultAssets.client.css, ['csslint']).on('change', plugins.livereload.changed);
gulp.watch(defaultAssets.client.sass, ['sass', 'csslint']).on('change', plugins.livereload.changed);
gulp.watch(defaultAssets.client.less, ['less', 'csslint']).on('change', plugins.livereload.changed);
gulp.watch(defaultAssets.server.gulpConfig, ['eslint']);
gulp.watch(defaultAssets.client.views).on('change', plugins.livereload.changed);
// }
});
// Run the project in development mode
gulp.task('default', function (done) {
runSequence('env:dev', ['watch', 'nodemon'], done);
});
I got the server working fine but there is nothing showing up on localhost:3000? How can i fix this?

Related

Refreshing a browser's cache while developing with gulp

My project's setup uses a combination of python's Flask on the backend which serves a fairly simple javascript React webpage using gulp.
Whether I'm debugging frontend code through Chrome or Firefox, I have to do a hard refresh multiple times before the changes make it to the browser. I see the gulp console log Finished 'transform' after N ms after each save, which leads me to believe it's the browsers fault.
I am not a front end engineer so I'm wondering what more experienced devs use. Hitting Cmd+Shift+R 5-20 times after each save is a little mind bogglingly inefficient.
current gulpfile.js:
'use strict';
var gulp = require('gulp'),
browserify = require('browserify'),
size = require('gulp-size'),
del = require('del'),
babelify = require('babelify'),
source = require('vinyl-source-stream'),
gutil = require('gulp-util');
var compiled_dir = './static/scripts/jsc';
var js_dir = './static/scripts/js';
function handle_error(err) {
gutil.log(err.message);
gutil.beep();
return process.exit(2);
}
gulp.task('transform', function () {
browserify({ entries: js_dir + '/main.js', debug: true })
.transform(babelify)
.bundle()
.on('error', handle_error)
.pipe(source('main.js'))
.pipe(gulp.dest(compiled_dir));
browserify({ entries: js_dir + '/userMgmt.js', debug: true })
.transform(babelify)
.bundle()
.on('error', handle_error)
.pipe(source('userMgmt.js'))
.pipe(gulp.dest(compiled_dir));
});
gulp.task('clean', function (cb) {
del([compiled_dir], cb);
});
gulp.task('default', ['clean'], function () {
gulp.start('transform');
gulp.watch(js_dir + "/*", ['transform']);
});
Method 1: Use this gulp-cache package to disable cache in development mode.
This will work:
var gulp = require('gulp');
var usemin = require('gulp-usemin');
var cache = require('gulp-cache');
gulp.task('default', function () {
return gulp.src('src/index.html')
.pipe(gulp.task('clear', function (done) {
return cache.clearAll(done);
});)
.pipe(usemin({
js: []
}))
.pipe(gulp.dest('dist'));
});
If you don't know how to use it, please update your question with gulp config file, I will configure you that.
Method 2: Configure your watcher.
$ npm install browser-sync --save-dev
var browserSync = require('browser-sync').create();
gulp.watch(['./**/*.{scss,css,html,py,js}'], ['clearCache', browserSync.reload]);
gulp.task('clearCache', function (done) {
return cache.clearAll(done);
});

Gulp wrong order

I have an Angular project that is supposed to make use of a library called angular-libphonenumber (https://github.com/cwill747/angular-libphonenumber).
I run:
bower install --save angular-libphonenumber
then:
gulp install
Now gulp thinks it is a good idea to inject angular-libphonenumber before angular itself:
<script src="bower_components/jquery/dist/jquery.js"></script>
...
<script src="bower_components/angular/angular.js"></script>
How do I tell gulp that this is not a good idea and inject lib-phonenumber after angular?
Here's the inject.js:
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
inject = require('gulp-inject'),
es = require('event-stream'),
naturalSort = require('gulp-natural-sort'),
angularFilesort = require('gulp-angular-filesort'),
bowerFiles = require('main-bower-files');
var handleErrors = require('./handle-errors');
var config = require('./config');
module.exports = {
app: app,
vendor: vendor,
test: test,
troubleshoot: troubleshoot
}
function app() {
return gulp.src(config.app + 'index.html')
.pipe(inject(gulp.src(config.app + 'app/**/*.js')
.pipe(naturalSort())
.pipe(angularFilesort()), {relative: true}))
.pipe(gulp.dest(config.app));
}
function vendor() {
var stream = gulp.src(config.app + 'index.html')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(inject(gulp.src(bowerFiles(), {read: false}), {
name: 'bower',
relative: true
}))
.pipe(gulp.dest(config.app));
return stream;
}
...

Gulpfile doesn't create bundle.js

I'm having some problems with my gulpfile
"use strict"
var gulp = require("gulp")
var browserify = require("browserify")
var source = require("vinyl-source-stream")
var livereload = require('gulp-livereload')
var watchify = require('watchify')
gulp.task("default", () => {
livereload.listen()
var bundler = browserify("./src/components/index.jsx")
.plugin(watchify, {ignoreWatch: './src/components/*'})
.transform("babelify", {presets: ["es2015", "react"]})
bundle(bundler)
bundler.on('update', function () {
bundle(bundler)
})
})
function bundle(bundler) {
bundler
.bundle()
.pipe(source('bundle.js')) // Set source name
.pipe(gulp.dest("./public/dist"))
.pipe(livereload()); // Reload the view in the browser
}
When I execute it using gulpI get the following messages
[02:06:23] Using gulpfile ~/react-rpi/gulpfile.js
[02:06:23] Starting
'default'... [02:06:23] Finished 'default' after 24 ms
But bundle.js is not created. Any key? Thanks in advance!
why don't you try this?
function bundle(bundler) {
return bundler.bundle().on('error', function (err) {
console.error(err.message)
this.emit('end')
})
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(plugins.sourcemaps.init({ loadMaps: true }))
.pipe(plugins.sourcemaps.write('./'))
.pipe(gulp.dest('./public/dist/js/'))
.pipe(plugins.livereload())
}
Then you can see what's happening

Using LowDB on Electron APP

I'm developing a basic app made with Electron and AngularJS. For this purpose I'm using the electron boilerplate (https://github.com/szwacz/electron-boilerplate) and for database, I'm using LowDB(https://github.com/typicode/lowdb).
I have been able to create a database(JSON) and read it from a script. But my problem is when I want to update and save. I can update, and the change is reflected on the JSON file, but when I start the app again, the JSON has the same data that at the beginning (it is overwritten).
I think it is a problem with the build task of Electron boilerplate, that always overwrites the file. I thought that when I did the task to release the app, it will fixes(npm run release), but not, it overwrites the json.
I am loading the database so:
import low from 'lowdb';
import storage from 'lowdb/file-sync';
import {
remote
}
from 'electron';
var fs = require('fs');
var app = remote.require('app');
const db = low(__dirname + '/db.json', {
storage
});
document.addEventListener('DOMContentLoaded', function() {
db('users').push({
'name': 'foo'
});
});
This script is loaded at the beginning, so it should add, every time that app is started, a new entry. The script is writting the new entry in JSON file but when the start is restarted, the JSON back to the previous state.
At the end, I am using the localStorage, but I would like to use LowDB to save the data locally.
Here is the task (gulp file) that I commented before about the build of app:
'use strict';
var pathUtil = require('path');
var Q = require('q');
var gulp = require('gulp');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
var plumber = require('gulp-plumber');
var jetpack = require('fs-jetpack');
var bundle = require('./bundle');
var generateSpecImportsFile = require('./generate_spec_imports');
var utils = require('../utils');
var projectDir = jetpack;
var srcDir = projectDir.cwd('./app');
var destDir = projectDir.cwd('./build');
var paths = {
copyFromAppDir: [
'./node_modules/**',
'./bower_components/**',
'./components/**',
'./scripts/**',
'./shared.services/**',
'./sections/**',
'./helpers/**',
'./db.json',
'./**/*.html',
'./**/*.+(jpg|png|svg|eot|ttf|woff|woff2)'
],
}
// -------------------------------------
// Tasks
// -------------------------------------
gulp.task('sass', ['clean'], function() {
console.log('Compiling SASS...');
gulp.src('app/styles/scss/main.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(destDir.path('styles')));
});
gulp.task('watch:sass', function() {
console.log('Watching SASS...');
var sassWatcher = gulp.watch(['app/styles/scss/*.scss','app/**/**/*.scss'], ['sass']);
sassWatcher.on('change', function(event) {
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
});
gulp.src('app/styles/scss/main.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(destDir.path('styles')));
});
gulp.task('clean', function (callback) {
return destDir.dirAsync('.', { empty: true });
});
var copyTask = function () {
return projectDir.copyAsync('app', destDir.path(), {
overwrite: true,
matching: paths.copyFromAppDir
});
};
gulp.task('copy', ['clean'], copyTask);
gulp.task('copy-watch', copyTask);
var bundleApplication = function () {
return Q.all([
bundle(srcDir.path('background.js'), destDir.path('background.js')),
bundle(srcDir.path('app.js'), destDir.path('app.js')),
bundle(srcDir.path('script.js'), destDir.path('script.js')),
]);
};
var bundleSpecs = function () {
return generateSpecImportsFile().then(function (specEntryPointPath) {
return bundle(specEntryPointPath, destDir.path('spec.js'));
});
};
var bundleTask = function () {
if (utils.getEnvName() === 'test') {
return bundleSpecs();
}
return bundleApplication();
};
gulp.task('bundle', ['clean'], bundleTask);
gulp.task('bundle-watch', bundleTask);
gulp.task('finalize', ['clean'], function () {
var manifest = srcDir.read('package.json', 'json');
// Add "dev" or "test" suffix to name, so Electron will write all data
// like cookies and localStorage in separate places for each environment.
switch (utils.getEnvName()) {
case 'development':
manifest.name += '-dev';
manifest.productName += ' Dev';
break;
case 'test':
manifest.name += '-test';
manifest.productName += ' Test';
break;
}
// Copy environment variables to package.json file for easy use
// in the running application. This is not official way of doing
// things, but also isn't prohibited ;)
manifest.env = projectDir.read('config/env_' + utils.getEnvName() + '.json', 'json');
destDir.write('package.json', manifest);
});
gulp.task('watch', function () {
watch('app/**/*.js', batch(function (events, done) {
gulp.start('bundle-watch', done);
}));
watch(paths.copyFromAppDir, { cwd: 'app' }, batch(function (events, done) {
gulp.start('copy-watch', done);
}));
watch('app/**/scss/*.scss', batch(function (events, done) {
gulp.start('watch:sass', done);
}));
watch('app/**/**/*.scss', batch(function (events, done) {
gulp.start('watch:sass');
}));
});
gulp.task('build', ['bundle', 'sass', 'copy', 'finalize']);
How you can see, in 'copyFromAppDir' there is a db.json. This file is my database, but I want update it and changes persist, but I am not be able to do that.
Kind regards!
It looks like your gulp task 'clean' is overwriting your db.json file. Because you are using lowDB, this is the same as overwriting your database. If you remove the line './db.json', from the 'copyFromAppDir' array the changes should persist.
Like this:
var paths = {
copyFromAppDir: [
'./node_modules/**',
'./bower_components/**',
'./components/**',
'./scripts/**',
'./shared.services/**',
'./sections/**',
'./helpers/**',
'./**/*.html',
'./**/*.+(jpg|png|svg|eot|ttf|woff|woff2)'
],
}

gulp browserify + reactify not creating bundle

When I run gulp I get an "updating!" and "updated!" log after saving main.js but there's no bundle ever built
gulpfile.js:
var watchify = require('watchify');
var reactify = require('reactify');
var concat = require('gulp-concat');
var util = require('gulp-util');
gulp.task('browserify', function() {
var bundler = browserify({
entries: ['./dist/main.js'], // Only need initial file, browserify finds the deps
transform: [reactify], // We want to convert JSX to normal javascript
debug: true, // Gives us sourcemapping
cache: {}, packageCache: {}, fullPaths: true // Requirement of watchify
});
var watcher = watchify(bundler);
return watcher
.on('update', function () { // When any files update
var updateStart = Date.now();
console.log('Updating!');
watcher.bundle() // Create new bundle that uses the cache for high performance
.pipe(source('main.js'))
.on('error', util.log)
// This is where you add uglifying etc.
.pipe(gulp.dest('/build/'));
console.log('Updated!', (Date.now() - updateStart) + 'ms');
})
.on('error', util.log)
.bundle() // Create the initial bundle when starting the task
.pipe(source('main.js'))
.pipe(gulp.dest('/build/'))
.on('error', util.log);
});
// I added this so that you see how to run two watch tasks
gulp.task('css', function () {
gulp.watch('styles/**/*.css', function () {
return gulp.src('styles/**/*.css')
.pipe(concat('main.css'))
.pipe(gulp.dest('build/'));
});
});
// Just running the two tasks
gulp.task('default', ['browserify', 'css']);
My file structure is
/build
/dist
-index.html
-main.js
/node_modules
/styles
gulpfile.js
I am not finding any errors and I am completely lost at this point. I've tried changing directories around and reloading everything but nothing works.
Update lines that contain gulp.dest('/build/') to gulp.dest(__dirname + '/build/'). Currently your file located at drive_root_dir/build/main.js

Resources