I'm running an Angular.js application and all the task management are made with grunt, for now I have three components that I'm watching in live reload, bower_components, invoices and users, eventually they are going to increase in number, so I would like to know if there's a way to call an external file like components.json and iterate through its n members. Here is my code:
// The grunt server settings
connect: {
options: {
port: 9000,
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect().use(
'/invoices',
connect.static(invoicesAppPathConfig.root)
),
connect().use(
'/users',
connect.static(usersAppPathConfig.root)
),
connect.static(secureAppPathConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= main.dist %>'
}
}
}
I have already created the component.json file:
{"data":[
{
"resource":"/bower_components",
"config":"./bower_components"
},
{
"resource":"/invoices",
"config":"invoicesAppPathConfig.root"
},
{
"resource":"/users",
"config":"usersAppPathConfig.root"
}
]}
And in the Gruntfile.js I created this variables, having in mind that I need to iterate in the content of data:
var components = require('./components.json');
var data = components.data;
Now I have the question, how can I do it this in the code?
middleware: function (connect) {
return [
connect.static('.tmp'),
// Here comes the data iteration
connect.static(secureAppPathConfig.app)
];
}
Thanks in advance.
Sure you can:
grunt.initConfig({
components: grunt.file.readJSON('components.json'),
[...]
});
More info on grunt.file here
You can also require it:
var components = require('./components.json');
Create the next variables:
var components = require('./components.json');
var data = components.data;
var arrayComponents = [];
Then in the options for livereload iterate the json data and add it to arrayComponents:
middleware: function (connect){
arrayComponents.push(connect.static('.tmp'));
// The modules to be watched are added
for(var i in data){
arrayComponents.push(connect().use(data[i].resource, connect.static(data[i].config)));
}
arrayComponents.push(connect.static(secureAppPathConfig.app));
return arrayComponents;
}
It works, but maybe it is not the most elegant solution.
I got nothing wrong in the terminal but Chrome doesn't answer to change on my html files and don't automatically reload the page.
I include 'livereload.js' in my index.html but i'm not sure if it's required.
Thanks for your help.
module.exports = function(grunt) {
// Load Grunt tasks declared in the package.json file
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
// Configure Grunt
grunt.initConfig({
// Grunt express - our webserver
// https://github.com/blai/grunt-express
express: {
all: {
options: {
bases: ['/Users/antoine/Dropbox/prog/projets/antoine/'],
port: 8080,
hostname: "localhost",
livereload: true
}
}
},
// grunt-watch will monitor the projects files
// https://github.com/gruntjs/grunt-contrib-watch
watch: {
all: {
files: '**/*.html',
options: {
livereload: true,
interval: 1500,
}
}
},
// grunt-open will open your browser at the project's URL
// https://www.npmjs.org/package/grunt-open
open: {
all: {
path: 'http://localhost:8080/index.html'
}
}
});
// Creates the `server` task
grunt.registerTask('server', [
'express',
'open',
'watch'
]);
};
My code is pretty simple, and the grunt file is,
module.exports = function(grunt) {
var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;
grunt.initConfig({
connect: {
server: {
options: {
hostname: "localhost",
keepalive: true,
base:['../web/'],
port: 8080,
middleware: function(connect, options) {
return [proxySnippet];
},
debug: true
}
}
}
});
// grunt.loadNpmTasks('grunt-connect-proxy');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.registerTask('default', [
'connect:server'
]);
};
there's an index.html, and the path is "../web/index.html". When I open
"http://localhost:8080"
it gives "Cannot GET /". Any idea why this is happening?
For directory structure like the following:
-node_modules
-templates
---index.html
---login.html
-Gruntfile.js
connect: {
options: {
port: 9000,
livereload: true,
hostname: 'localhost',
},
livereload: {
options: {
open: true,
base: ['templates/']
}
}
}
This open the complete directory structure of templates on the browser to navigate to any html page.
Remove the middleware proxy, like this:
module.exports = function(grunt) {
var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;
grunt.initConfig({
connect: {
server: {
options: {
hostname: "localhost",
keepalive: true,
base:['../web/'],
port: 8081,
debug: true
}
}
}
});
// grunt.loadNpmTasks('grunt-connect-proxy');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.registerTask('default', [
'connect:server'
]);
};
And must work.
On my MEAN stack application, I'm trying make changes to the HTML view files and see those changes as I make them using Grunt's livereload.
Grunt's livereload is working fine in the sense that it detects changes in my HTML files and refreshes the page during development. However, the actual changes are not reflecting on the page. If I push the files up the server, and reload the publicly available site, the changes are there. But I still can't see the changes while I'm developing.
I'm 99% sure that the problem has to do with the server is using the "build" files or something rather than the files located in the /public folder. However, I'm new to using the back-end and the MEAN stack and can't figure out what file the browser is showing or where this file is. Could anyone give any guidance on how to figure out what file the browser is displaying and what I can do to show HTML changes I make as I make them?
Here is my gruntfile if this helps. The below files I'm making changes to are watchFiles.clientViews.
'use strict';
module.exports = function(grunt) {
// Unified Watch Object
var watchFiles = {
serverViews: ['app/views/**/*.*'],
serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js'],
clientViews: ['public/modules/**/views/**/*.html'],
clientJS: ['public/js/*.js', 'public/modules/**/*.js'],
clientCSS: ['public/modules/**/*.css'],
mochaTests: ['app/tests/**/*.js']
};
// Project Configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
options: { livereload: true },
serverViews: {
files: [watchFiles.serverViews],
options: {
livereload: true
}
},
serverJS: {
files: watchFiles.serverJS,
tasks: ['jshint'],
options: {
livereload: true
}
},
clientViews: {
files: watchFiles.clientViews,
options: {
livereload: true,
}
},
clientJS: {
files: watchFiles.clientJS,
tasks: ['jshint'],
options: {
livereload: true
}
},
clientCSS: {
files: watchFiles.clientCSS,
tasks: ['csslint'],
options: {
livereload: true
}
}
},
jshint: {
all: {
src: watchFiles.clientJS.concat(watchFiles.serverJS),
options: {
jshintrc: true
}
}
},
csslint: {
options: {
csslintrc: '.csslintrc',
},
all: {
src: watchFiles.clientCSS
}
},
uglify: {
production: {
options: {
mangle: false
},
files: {
'public/dist/application.min.js': 'public/dist/application.js'
}
}
},
cssmin: {
combine: {
files: {
'public/dist/application.min.css': '<%= applicationCSSFiles %>'
}
}
},
nodemon: {
dev: {
script: 'server.js',
options: {
nodeArgs: ['--debug'],
ext: 'js,html',
watch: watchFiles.serverViews.concat(watchFiles.serverJS)
}
}
},
'node-inspector': {
custom: {
options: {
'web-port': 1337,
'web-host': 'localhost',
'debug-port': 5858,
'save-live-edit': true,
'no-preload': true,
'stack-trace-limit': 50,
'hidden': []
}
}
},
ngAnnotate: {
production: {
files: {
'public/dist/application.js': '<%= applicationJavaScriptFiles %>'
}
}
},
concurrent: {
default: ['nodemon', 'watch'],
debug: ['nodemon', 'watch', 'node-inspector'],
options: {
logConcurrentOutput: true,
limit: 10
}
},
env: {
test: {
NODE_ENV: 'test'
}
},
mochaTest: {
src: watchFiles.mochaTests,
options: {
reporter: 'spec',
require: 'server.js'
}
},
karma: {
unit: {
configFile: 'karma.conf.js'
}
}
});
// Load NPM tasks
require('load-grunt-tasks')(grunt);
// Making grunt default to force in order not to break the project.
grunt.option('force', true);
// A Task for loading the configuration object
grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() {
var init = require('./config/init')();
var config = require('./config/config');
grunt.config.set('applicationJavaScriptFiles', config.assets.js);
grunt.config.set('applicationCSSFiles', config.assets.css);
});
// Default task(s).
grunt.registerTask('default', ['lint', 'concurrent:default']);
// Debug task.
grunt.registerTask('debug', ['lint', 'concurrent:debug']);
// Lint task(s).
grunt.registerTask('lint', ['jshint', 'csslint']);
// Build task(s).
grunt.registerTask('build', ['lint', 'loadConfig', 'ngAnnotate', 'uglify', 'cssmin']);
// Test task.
grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);
};
In addition, here is the file structure to my MEAN stack. The highlighted below is where the HTML file that I'm making changes to is located.
Please let me know if there is any other code or info I could provide that would make solving this problem easier. Thank you.
Update: Content of Server.js
Here is my server.js content:
'use strict';
/**
* Module dependencies.
*/
var init = require('./config/init')(),
config = require('./config/config'),
mongoose = require('mongoose');
/**
* Main application entry file.
* Please note that the order of loading is important.
*/
// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
if (err) {
console.error('\x1b[31m', 'Could not connect to MongoDB!');
console.log(err);
}
});
// Init the express application
var app = require('./config/express')(db);
// Bootstrap passport config
require('./config/passport')();
// Start the app by listening on <port>
app.listen(config.port);
// Expose app
exports = module.exports = app;
// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);
It's hard to tell exactly what your "server.js" is serving without seeing the contents of it, but if my assumption is correct and you are serving the contents of the "public" directory, you don't have any sort of task being fired by watch that facilitates copying the contents of your changed files into your "public" directory. It looks like this happens initially when your server is started (by running the build task), but not run subsequently whenever something is changed.
I would suggest modifying your watch tasks to perform some of the build-related tasks on your files as they are changed. Since your build-related tasks are physically copying the changes to the "public" directory for you as part of their jobs, you should finally see the results of your changes. Here's an example of your watch task list that's modified to copy your JS and CSS files on change:
watch: {
options: { livereload: true },
serverViews: {
files: [watchFiles.serverViews],
options: {
livereload: true
}
},
serverJS: {
files: watchFiles.serverJS,
tasks: ['jshint', 'loadConfig', 'ngAnnotate', 'uglify'],
options: {
livereload: true
}
},
clientViews: {
files: watchFiles.clientViews,
options: {
livereload: true,
}
},
clientJS: {
files: watchFiles.clientJS,
tasks: ['jshint', 'loadConfig', 'ngAnnotate', 'uglify'],
options: {
livereload: true
}
},
clientCSS: {
files: watchFiles.clientCSS,
tasks: ['csslint', 'cssmin'],
options: {
livereload: true
}
}
},
One last thing: Assuming your views don't need to have any modifications done to them post-change, you can simply straight-up copy them to the public directory when they are changed. Take a look at grunt-contrib-copy for doing simple file copying between directories.
I was facing the same issue and solved it by disabling the cache in the network tab
Go to Inspect -> Network and make sure disable cache is checked.
Hope this helps someone in future :)
I have been working all day on trying to get my proxies set up in my Gruntfile. Here is my Gruntfile:
var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;
module.exports = function(grunt) {
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.initConfig({
connect:{
livereload: {
options: {
middleware: function (connect) {
return [proxySnippet];
}
}
},
options: {
port: 9000,
base: 'app',
keepalive: true,
livereload: true
},
proxies: [
{
context: '/public/api',
host: 'localhost',
port: 8182,
https: false,
rewrite: {
'^/public/api': ''
}
}
]
}
});
grunt.registerTask('server', ['less', 'configureProxies', 'connect', 'connect', 'watch', 'open:dev']);
};
When I run my grunt server I can only hit my proxy. If I try to just hit anything other than the proxy I get a 404. What is giving me this issue?
I also had a lot of trouble setting up a proxy using grunt-connect-proxy.
Digging in the source code of grunt-contrib-connect, I realized that it uses the nodeJs Connect framework behind the scene.
Internally the middleware option defaults to this function:
function (connect, options) {
var middlewares = [];
if (!Array.isArray(options.base)) {
options.base = [options.base];
}
var directory = options.directory || options.base[options.base.length - 1];
options.base.forEach(function (base) {
// Serve static files.
middlewares.push(connect.static(base));
});
// Make directory browse-able.
middlewares.push(connect.directory(directory));
return middlewares;
}
Which basically adds the connect.static and the connect.directory middlewares to an array passed to the connect(middlewares) constructor.
Knowing that, we can make use of the proxy-middleware nodeJs package like this:
connect: {
server: {
options: {
port: 9002,
keepalive: true,
middleware: function (connect, options) {
// Proxy all requests to target the local application.
var proxyOptions = require('url').parse('http://localhost:8080/');
proxyOptions.route = '/api';
return [
require('proxy-middleware')(proxyOptions), // Include the proxy first.
connect.static(options.base), // Serve static files.
connect.directory(options.base) // Make empty directories browse-able.
];
}
}
}
}
Basically we are adding a middleware to the middleware array.
This new proxy middleware will translate any incoming request like http://localhost:9002/api/ into http://localhost:8080/