I was wondering if anyone has got grunt karma to run just one spec that is changed on watch. This is my config below. The problem is that the line grunt.config('karma.unit.options.files', filepath); doesn't seem to be doing anything as all the specs still get run however foo does get output before the karma:unit:run gets fired.
grunt.initConfig({
karma: {
unit: {
configFile: 'karma.conf.js',
background: true,
singleRun: false,
options: {
files: allFilesArray
}
}
},
watch: {
options: {
spawn: false,
livereload: true
},
karma: {
files: ['js/spec/**/*.spec.js', 'js/src/**/*.js'],
tasks: ['karma:unit:run']
}
}
})
grunt.event.on('watch', function (action, filepath){
console.log('foo');
grunt.config('karma.unit.options.files', filepath);
});
Is there anyone out there who has achieved running one spec in the terminal on file change? We have thousands of tests so it is starting to get slow.
Thanks,
Alex
I got this to work. Basically, you use watch with an event handler to dynamically change the karma config whenever a file changes. Here's the rundown:
My Grunt config has two karma tasks: "all" and "one". "all" runs all of them, and "one" only runs a single file which it does not know beforehand.
grunt.initConfig({
// ...
karma: {
all: {
configFile: 'karma.conf.js',
browsers: ['PhantomJS'],
singleRun: true,
options: {
files: [
'bower_components/jquery/dist/jquery.js', // dependencies
'src/js/**/*.js', // js source files
'src/js/**/*.spec.js' // unit test files
]
}
},
one: {
configFile: 'karma.conf.js',
browsers: ['PhantomJS'],
singleRun: true,
files: [
{src: 'bower_components/jquery/dist/jquery.js'}, // dependencies
{src: ['src/js/**/*.js','!src/js/**/*.spec.js']} // source files
// (exclude the unit test files)
// watchEventListener will add the unit test file to run
]
}
},
// ...
});
And then later in my gruntfile, I add a listener for watch events. This listener updates the karma:one task and adds the unit test file. We keep a copy of the original files array, or else our additions would persist and accumulate through the lifetime of the watch task.
// when a unit test changes, execute only it
var original_karmaOne_files = grunt.config.get('karma.one.files'); // keep the original files array
grunt.event.on('watch', function watchEventListener(action, filepath, target){
// this handler handles ALL watch changes. Try to filter out ones from other watch tasks
if (target == 'js_spec') handleJSHintSpec();
// ---------------------
function handleJSHintSpec() {
if (action == 'deleted') return; // we don't need to run any tests when a file is deleted
// this will probably fail if a watch task is triggered with multiple files at once
// dynamically change the config
grunt.config.set('karma.one.files', [].concat(original_karmaOne_files, [{src: filepath}]));
}
});
And here is my gruntfile's watch task:
watch: {
// ...
// when js spec files change,
// lint them
// run unit tests
js_spec: {
options: {
interrupt: true
},
files: 'src/js/**/*.spec.js',
tasks: ['jshint:js_spec', 'karma:one']
},
// ...
}
My karma.conf.js file is pretty default, but its files array is empty. Actually, I commented it out, so the property is undefined.
// list of files / patterns to load in the browser
//files: [], // specified in the gruntfile
TL; DR: Use karma:unit everywhere instead of karma:unit:run and use grunt.event.on('watch', function(){}); to edit the karma config to only include the test files you want to run.
I have this working, but it might not be what you want. I'm starting the server up again every time I save a file. Further explanation is below. Here is some of the config:
watch: {
tests: {
files: 'tests/**/*.js',
tasks: ['karma:unit']
},
tsChanged: {
files: config.tsFiles,
tasks: [
'ts',
'karma:unit'
]
}
}
grunt.event.on('watch', function(action, filepath){
grunt.config(['karma', 'unit', 'files'], [{
src: [
path/to/your/source/files,
path/to/your/test/file,
]
}]);
});
It seems to me that karma loads all of the app files and the test files into the browser whenever it starts the server. In your case, that would be when you enter "grunt karma:unit:start watch" into the command line. So here, I used "grunt watch" and just added a "karma:unit" to the process. Then I caught the save event and updated the karma config before it started up the server.
Hope this helps.
Using a combination of yargs and some runtime-magic, I do this:
var argv = require('yargs')
.default('t', '*.js')
.alias('t', 'tests')
.describe('t', 'A file or file pattern of the test files to run, relative to the test/unit dir')
.help('?')
.alias('?', 'help')
.argv;
var filesToLoad = ['src/**/*.js', 'test/unit/helpers/*.js'];
filesToLoad.push(path.join('test/unit/**', argv.t));
gulp.task('tdd', function (done) {
karma.start({
configFile: __dirname + '/../../karma.conf.js',
jspm: {
loadFiles: filesToLoad,
}
}, function(e) {
done();
});
});
Which takes a test file / path pattern as an argument to gulp and loads that in preference to all the files.
Based on the answer of Matthias and the comments my Grundfile.js is:
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
karma: {
all: {
configFile: 'karma.conf.js',
background: true,
files: [
{ src: './Leen.Managementsystem/bower_components/jquery/dist/jquery.js' },
{ src: './Leen.Managementsystem/bower_components/globalize/lib/globalize.js' },
{ src: './Leen.Managementsystem/bower_components/**/*.js', included: false },
{ src: './Leen.Managementsystem.Tests/App/test/mockFactory.js', included: false },
{ src: './Leen.Managementsystem/App/**/*.js', included: false },
{ src: './Leen.Managementsystem.Tests/App/test/*.js', included: false },
{ src: './Leen.Managementsystem.Tests/App/**/*.spec.js', included: false },
{ src: './Leen.Managementsystem.Tests/App/test-main.js' }
]
},
one: {
configFile: 'karma.conf.js',
files: [
{ src: './Leen.Managementsystem/bower_components/jquery/dist/jquery.js' },
{ src: './Leen.Managementsystem/bower_components/globalize/lib/globalize.js' },
{ src: './Leen.Managementsystem/bower_components/**/*.js', included: false },
{ src: './Leen.Managementsystem.Tests/App/test/mockFactory.js', included: false },
{ src: './Leen.Managementsystem/App/**/*.js', included: false },
{ src: './Leen.Managementsystem.Tests/App/test/*.js', included: false },
// (do not inlcude the *.spec.js files here! The watch event listener will add the single spec file to run)
{ src: './Leen.Managementsystem.Tests/App/test-main.js' }
]
}
},
watch: {
spec_js: {
options: {
interrupt: true,
spawn: false
},
files: 'Leen.Managementsystem.Tests/App/**/*.spec.js',
tasks: ['karma:one:start']
}
}
});
var originalKarmaOneFiles = grunt.config.get('karma.one.files'); // keep the original files array
grunt.event.on('watch', function watchEventListener(action, filepath, target) {
if (target === 'spec_js') {
handleChangedSpecFile();
}
function handleChangedSpecFile() {
if (action === 'deleted') {
return;
}
var testFilePath = "./" + filepath.replace(/\\/g, "/");
grunt.log.writeln(['Running single karma test for: ' + testFilePath]);
var updatedFiles = originalKarmaOneFiles.concat([{ src: testFilePath, included: false }]);
grunt.config.set('karma.one.files', updatedFiles);
}
});
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['karma:all','watch']);
};
karma.conf.js:
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '', //the solution root path, e.g. D:\Energienetzwerke\trunk
// frameworks to use
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'./Leen.Managementsystem/bower_components/jquery/dist/jquery.js',
'./Leen.Managementsystem/bower_components/globalize/lib/globalize.js',
{ pattern: './Leen.Managementsystem/bower_components/**/*.js', included: false },
{ pattern: './Leen.Managementsystem.Tests/App/test/mockFactory.js', included: false },
{ pattern: './Leen.Managementsystem/App/**/*.js', included: false },
{ pattern: './Leen.Managementsystem.Tests/App/test/*.js', included: false},
{ pattern: './Leen.Managementsystem.Tests/App/**/*.spec.js', included: false},
'./Leen.Managementsystem.Tests/App/test-main.js'
],
// list of files to exclude
exclude: [
'./Leen.Managementsystem/App/main.js'
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress', 'coverage', 'notify', 'htmlDetailed', 'xml'],
coverageReporter: {
dir: './Leen.Managementsystem.Tests/testCoverage',
reporters: [
{ type: 'html',subdir: 'html'},
{ type: 'cobertura',subdir: 'xml', file: 'coverage.xml' },
{ type: 'lcov', subdir: 'lcov' },
{ type: 'text-summary' }
]
},
notifyReporter: {
reportEachFailure: true, // Default: false, Will notify on every failed spec
reportSuccess: false // Default: true, Will notify when a suite was successful
},
htmlDetailed: {
autoReload: true,
dir: './Leen.Managementsystem.Tests/testResults'
},
preprocessors: {
// source files, that you wanna generate coverage for
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
'./Leen.Managementsystem/App/**/*.js': ['coverage']
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false, //watching is done by Gruntfile.js to only execute changed tests
usePolling: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome_With_Saved_DevTools_Settings'],
customLaunchers: {
Chrome_With_Saved_DevTools_Settings: {
base: 'Chrome',
chromeDataDir: './.chrome'
}
},
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true
});
};
package.json:
{
"name": "solution",
"version": "1.0.0",
"description": "contains packages that are needed for running karma",
"main": "./Leen.Managementsystem.Tests/App/test-main.js",
"dependencies": {
"grunt": "1.0.1",
"grunt-cli": "1.2.0",
"grunt-contrib-watch": "1.0.0",
"grunt-karma": "2.0.0",
"jasmine-core": "2.6.4",
"karma": "1.7.0",
"karma-chrome-launcher": "2.2.0",
"karma-cli": "1.0.1",
"karma-coverage": "1.1.1",
"karma-firefox-launcher": "1.0.1",
"karma-html-detailed-reporter": "1.1.20",
"karma-ie-launcher": "1.0.0",
"karma-jasmine": "1.1.0",
"karma-notify-reporter": "1.0.1",
"karma-phantomjs-launcher": "1.0.4",
"karma-requirejs": "1.1.0",
"karma-xml-reporter": "0.1.4",
"requirejs": "2.3.4"
},
"devDependencies": {},
"scripts": {
"test": "karma run"
},
"author": "LEEN",
"license": "private"
}
Related
I've got several projects that each use an identical Gruntfile to run tasks and put the output in their own dist folder. Folder setup:
MyProjects
- Project1
- src
- dist
- Project2
- src
- dist
.....
I can't figure out how to run Grunt at the top level (MyProjects) and still have the output generated in the correct dist folder dynamically.
Is there a way I can have Grunt put the output in the correct dist folder without having to hard code it into the Gruntfile? Something like:
dist: {
files: {
// destination : source js
'<% ProjectName %>/dist/app.js': '<% ProjectName %>/src/app.js'
},
Thanks
module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
watch: {
scripts: {
files: ['src/**/*.js'],
tasks: ['browserify', 'file_append', 'concat'],
options: {
spawn: false
}
},
sass: {
files: "src/scss/*.scss",
tasks: ['sass', 'file_append', 'concat']
}
},
sass: {
dist: {
options: {
style: 'expanded'
},
files: {
// destination // source file
"format/css/styles.css": "src/scss/styles.scss"
}
},
options: {
sourcemap: "none",
style: "compact",
noCache: true
}
},
file_append: {
default_options: {
files: [
// Development build
{
append: "",
prepend: "",
input: "format/app.js",
output: "format/dev.app.js"
},
{
append: "</style>`)",
prepend: "document.body.insertAdjacentHTML('afterbegin', `\n<style>\n",
input: "format/css/styles.css",
output: "format/css/dev.styles.html"
},
// Production build
{
append: "</script>",
prepend: "<script>\n",
input: "format/app.js",
output: "format/prod.app.html"
},
{
append: "</style>",
prepend: "<style>\n",
input: "format/css/styles.css",
output: "format/css/prod.styles.html"
}
]
}
},
concat: {
options: {
seperator: '\n'
},
// Development build
dev: {
src: ['format/dev.app.js', 'format/css/dev.styles.html'],
dest: 'dev/dev.app.js'
},
// Production build
prod: {
src: ['format/prod.app.html', 'format/css/prod.styles.html'],
dest: 'dist/prod.app.html'
}
},
browserify: {
dist: {
files: {
// destination for transpiled js : source js
'format/app.js': 'src/app.js'
},
options: {
transform: [
[
'babelify', {
presets: "es2015",
comments: false,
plugins: "transform-object-rest-spread"
}
]
],
browserifyOptions: {
debug: false
}
}
}
}
});
grunt.registerTask('default', [
'sass',
'browserify:dist',
'file_append',
'concat',
'watch'
]);
};
There's a couple ways you can tackle this.
One option is to overload the arguments you pass to the task & include the folder name you wish to target.
grunt sass:dist:Project1
The additional argument is accessible via lodash templates which are a part of the GruntJS framework, and allows the configuration to be set at the time the task is ran:
sass: {
dist: {
options: {
style: 'expanded'
},
files: {
// destination // source file
"MyProjects/<%= grunt.task.current.args[0] %>/format/css/styles.css": "MyProjects/<%= grunt.task.current.args[0] %>/src/scss/styles.scss"
}
},
options: {
sourcemap: "none",
style: "compact",
noCache: true
}
}
This approach works in the context of the function that's executing, but it wouldn't continue to pass the args to the next task. To do that, we need to add a custom task which will set a configuration object before executing the task list:
grunt.registerTask("build", (project) => {
const buildConfig = { project };
grunt.config.set("build", buildConfig);
grunt.task.run([
'sass',
'browserify:dist',
'file_append',
'concat',
'watch'
]);
});
Now when we run grunt build:Project1, your custom task build will run and set the property we passed in the grunt config object. We can then reference that value in our other grunt config objects using lodash like we did for the first option. To access config values with lodash templates, we just have to provide the config pointer in json notation:
files: {
"MyProjects/<%= build.project %>/format/css/styles.css": "MyProjects/<%= build.project %>/src/scss/styles.scss"
}
Grunt compiles the configs required for a task at the time they're run & will process the lodash templates then, allowing you to inject your project name into a task. Since we stored the value in the config object, the value will persist through until grunt completes and exits.
Here is my problem.
All mentioned paths as per below gruntfile.js are watched fine (shown in grunt --verbose -v). Livereload fires whenever I change files (at least --verbose shows livereload fires). But the page is live reloaded ONLY in case I change my /development/index.html (in Sublime Text) or /less/mainpage.less (with contrib-less).
If I change development/img//* or anyting in /test//*, livereload FIRES but do not RELOAD my page.
I would really appreciate if someone could help.
Here is my folder structure:
source location root: /development/
destination location root: /test/
Here is my gruntfile.js:
module.exports = function(grunt) {
grunt.initConfig({
watch: {
livereload: {
files: ['development/*.html', "test/**/*", "development/img/**/*"],
options: {
livereload: true,
spawn: false
}
},
// watch tasks start here
scripts: {
files: ['development/js/**/*.js'],
tasks: ['concat']
},
html: {
files: ['development/*.html'],
tasks: ['copy:html']
},
less_compile: {
files: ['development/a_source/less/**/*.less'],
tasks: ['less', "stripCssComments"]
},
images: {
files: ['development/img/**/*'],
tasks: ['tinyimg']
}
},
// runs local server for livereload
connect: {
sever: {
options: {
hostname: 'localhost',
port: 3000,
base: 'test/',
livereload: true
}
}
},
// *** *.html, *.img copy task here
copy: {
html: {
expand: true,
cwd: 'development',
src: '*.html',
dest: 'test/',
}
},
// *** LESS tasks here
less: {
compile: {
options: {
paths: ["development/b_components/less/"]
},
files: {
"temp/css/style.css": "development/a_source/less/style.less"
}
}
}, // compiles less and put compiled version into /temp/css/style.test
stripCssComments: {
dist: {
files: {
'test/css/style.css': 'temp/css/style.css'
}
}
}, // strips comments from /temp/css/style.css and copies it to /test/
// minify images
tinyimg: {
dynamic: {
files: [{
expand: true, // Enable dynamic expansion
cwd: 'development/img/', // Src matches are relative to this path
src: ['**/*.{png,jpg,gif}'], // Actual patterns to match
dest: 'test/img/' // Destination path prefix
}]
}
}
}); //initConfig
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-strip-css-comments');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-tinyimg');
grunt.registerTask('default', ["connect", "watch"]);
}; //wrapper function
Try this
livereload:{
options:{
livereload:'<%= connect.options.livereload %>'
},
files:[
'app/{,*/}*.html',
'app/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
This should reload if you make changes in your images folder. (Customize the URL according to your structure.)
OK. I just wanted to wrap up after I solved all my problems.
I arrived at the following acceptably working setup:
- as per above: Grunt serves as only "files" worker doing all compile / concat / copy etc.
work.
- browser-sync is my local server (with bunch of other vital capabilities) and fast livereload tool, that additionally syncs
several open test windows (https://browsersync.io/).
- Divvy: great addition to my workflow capable of arranging windows on the desktop on the fly (http://mizage.com/divvy/).
Update:
Soon after I switched to Gulp + Browsersync. I could not be satisfied more. Gulp works roughly 10 times faster and Browsersync is smooth and convenient.
Here is my gulpfile.js example just to demonstrate the tasks this pair manages for me:
var gulp = require("gulp"),
gutil = require("gulp-util"),
less = require('gulp-less'),
concat = require('gulp-concat'),
browserify = require('gulp-browserify'),
browserSync = require('browser-sync').create(),
gulpcopy = require('gulp-copy'),
newer = require('gulp-newer'),
imagemin = require('gulp-imagemin'),
autoprefixer = require('gulp-autoprefixer'),
uglifyjs = require('gulp-uglify'),
cleanCSS = require('gulp-clean-css'),
uglifycss = require('gulp-uglifycss'),
htmlmin = require('gulp-htmlmin'),
htmlhint = require("gulp-htmlhint"),
htmlv = require('gulp-html-validator'),
validatecss = require('gulp-w3c-css'),
sourcemaps = require('gulp-sourcemaps');
var lessMain = ["src/styles/less/styles.less"],
lessSources = ["src/styles/less/*.less", "src/styles/**/*.css"],
jsSources = "src/js/*.js",
jsonSources = ["src/js/*.json"],
htmlSources = ["src/html/*.html"],
imgSources = ["z_design/images/processed/**/*.*"],
imgDest = ["public/img/**/*.*"],
cssTemp = ["src/temp/css/styles.css"],
srcjQuery = "node_modules/jquery/dist/jquery.min.js",
srcMustache = "node_modules/mustache/mustache.min.js";
gulp.task("message", function() {
gutil.log("============= Gulp script started ==============");
});
// compiling less
gulp.task("less-compile", function() {
gulp.src(lessMain)
// switches sourcemaps on/off
.pipe(sourcemaps.init())
.pipe(less()
.on("error", gutil.log))
// switches sourcemaps on/off
.pipe(sourcemaps.write())
// change .dest("folder") to "public/css"
// to make no-autoprefix
// or to "src/temp/css/" to switch autoprefix on
.pipe(gulp.dest("public/css"))
});
// prepare & copy js files
gulp.task("js", function() {
gulp.src([srcjQuery, srcMustache, jsSources])
.pipe(concat("script.js"))
.pipe(gulp.dest("public/js/"))
});
// .pipe(browserify())
// {bundleExternal: false}
// copy JSON files
gulp.task("copyjson", function() {
gulp.src(jsonSources)
.pipe(newer("public/js/"))
.pipe(gulpcopy("public/js/", {
prefix: 2
}))
});
// copy html files
gulp.task("copyhtml", function() {
gulp.src(htmlSources)
.pipe(newer("public/"))
.pipe(gulpcopy("public/", {
prefix: 2
}))
});
// --- minify & compress images: 2 tasks - auto and manual
// minify & copy images - manual task
gulp.task("img-ondemand", function() {
gulp.src("z_design/images/unprocessed/**/*.*")
.pipe(newer("public/img/"))
.pipe(imagemin({
progressive: true
}))
.pipe(gulp.dest('z_design/images/processed/'))
});
// minify & copy images - automatic task
gulp.task("processimages", function() {
gulp.src(imgSources)
.pipe(newer("public/img/"))
.pipe(imagemin({
progressive: true
}))
.pipe(gulp.dest('public/img/'))
});
// --- end
// forced reload
gulp.task("reload", function() {
browserSync.reload();
});
// autoprefixer
gulp.task("autoprefix", function() {
gulp.src(cssTemp)
.pipe(autoprefixer({
browsers: ['last 3 versions', 'safari 5', 'ie 8', 'ie 9', 'ie 10', "ie11", 'opera 12.1', 'ios 6', 'android 4'],
cascade: false
}))
.pipe(gulp.dest("public/css/"))
});
// watching for changes
gulp.task("watch", function() {
gulp.watch(lessSources, ["less-compile"])
gulp.watch(jsSources, ["js"])
gulp.watch(jsonSources, ["copyjson"])
gulp.watch(htmlSources, ["copyhtml"])
gulp.watch(imgSources, ["processimages"])
gulp.watch(imgDest, ["reload"])
gulp.watch("src/temp/css/styles.css", ["autoprefix"])
});
// serving localhost
gulp.task('browser-sync', function() {
browserSync.init({
server: ["public", "src"],
watchTask: true,
open: false,
files: ["public/*.html", "public/css/*.css", "public/js/*.*",
"public/img/**/*.*"]
});
});
// === production preparations: RUN SEPARATE TASKS ON DEMAND ===
// --- minify & compress HTML, CSS, JS
// uglify JS
gulp.task("compress-js", function() {
gulp.src("public/js/script.js")
.pipe(uglifyjs())
.pipe(gulp.dest('public/js/'))
});
// uglify CSS
gulp.task('uglify-css', function() {
gulp.src('public/css/styles.css')
.pipe(uglifycss({
"debug": true,
"uglyComments": true
}))
.pipe(gulp.dest('public/css/'));
});
// compress HTML
gulp.task('compress-html', function() {
return gulp.src('src/html/*.html')
.pipe(htmlmin({
collapseWhitespace: true,
removeComments: true
}))
.pipe(gulp.dest('public/'));
});
// --- lint HTML and validate CSS
// lint html
gulp.task('lint-html', function() {
gulp.src("public/*.html")
.pipe(htmlhint())
.pipe(htmlhint.reporter())
});
// validate html
// Option format set to html
gulp.task('validate-html', function() {
gulp.src('public/*.html')
.pipe(htmlv({
format: 'html'
}))
.pipe(gulp.dest('src/temp/validation/'));
});
// add css validation
gulp.task('validate-css', function() {
gulp.src('public/css/*.css')
.pipe(validatecss())
.pipe(gulp.dest('src/temp/validation/'));
});
gulp.task("validate", ["validate-html", "validate-css", "lint-html"]);
gulp.task("compress", ["compress-js", "uglify-css", "compress-html"]);
gulp.task("default", ["watch", "browser-sync"]);
// =======================
For some reason running grunt from the terminal doesn't work. When I run grunt dev and open http://localhost:8000/ it works, but when I just use grunt it says This site can’t be reached. localhost refused to connect.
Any ideas what I am missing?
'use strict';
var path = require('path');
var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;
var folderMount = function folderMount(connect, point) {
return connect.static(path.resolve(point));
};
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
build: {
src: [".sass-cache"]
}
}, // end clean
sass: {
dist: {
options: {
style: 'expanded',
noCache: true
},
files: {
'app/production/css/style.css': 'app/scss/style.scss'
}
}
}, // end sass
cssmin: {
target: {
files: [{
expand: true,
cwd: 'app/production/css',
src: ['*.css', '!*.min.css'],
dest: 'app/production/css',
ext: '.min.css'
}]
}
}, //end cssmin
connect: {
server: {
options: {
port: 8000
}
}
}, // end connect
uglify: {
options: {
mangle: false
},
my_target: {
files: {
'app/production/js/app.min.js': ['app/js/module.js', 'app/js/config.js', 'app/js/factory.js', 'app/js/filter.js', 'app/js/PotatoAppController.js']
}
}
}, // end js minify
watch: { // this is a watcher, to run this in terminal write: grunt watch
options: {
dateFormat: function(time) {
grunt.log.writeln('The watch finished in ' + time + 'ms at' + (new Date()).toString());
grunt.log.writeln('Waiting for new changes ...');
},
livereload: true
},
css: {
files: 'app/scss/style.scss',
tasks: ['sass', 'cssmin']
},
jsmin: {
files: 'app/js/*.js',
tasks: ['uglify']
},
html: {
files: ['app/views/**/*.html'],
options: {
livereload: true
}
}
} // end watch
});
grunt.loadNpmTasks('grunt-contrib-watch'); // Load the plugin that provides the "watch" task.
grunt.loadNpmTasks('grunt-contrib-cssmin'); // Load the plugin that provides the "cssmin" task.
grunt.loadNpmTasks('grunt-contrib-sass'); // Load the plugin that provides the "sass" task.
grunt.loadNpmTasks('grunt-contrib-uglify'); // Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-livereload'); // Load the plugin that provides the "livereload" task.
grunt.loadNpmTasks('grunt-contrib-connect'); // Load the plugin that provides the "connect" task.
grunt.loadNpmTasks('grunt-contrib-clean'); // Load the plugin that provides the "clean" task.
grunt.registerTask('default', ['watch']); // this is the default command, use in terminal 'grunt'
grunt.registerTask('dev', ['connect', 'sass', 'cssmin', 'uglify', 'clean', 'watch']); // use 'grunt dev' for development
};
Once you execute 'grunt', 'default' command will be executed.
In your case, only 'watch' task is executed.
grunt.registerTask('default', ['watch']);
If you want to reach 'localhost', you need to run 'connect' module.
'watch' task is just watching file changes. not launch web-server.
'connect' is for launching web-server.
Thanks.
I would like my Gruntfile to use my package.json to read my dependancies (installed via npm) and concatenate all my javascript files into a single file that I can then minify. Currently I only have one production dependency but I plan on adding others and I'd like a way for grunt to figure out that I've already added one and include it into the build path.
Here is my package.JSON:
{
"name": "template",
"version": "1.0.0",
"description": "A template written by author",
"main": "index.html",
"author": "author",
"license": "ISC",
"devDependencies": {
"grunt": "^0.4.5",
"grunt-contrib-concat": "^0.5.1",
"grunt-contrib-connect": "^0.9.0",
"grunt-contrib-jshint": "^0.11.0",
"grunt-contrib-uglify": "^0.8.0",
"grunt-contrib-watch": "^0.6.1"
},
"dependencies": {
"d3": "^3.5.5"
}
}
Here is my grunt file
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
config: grunt.file.readJSON('config.json')
});
// Load the plugin that provides the watch tasks.
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.config('watch', {
all: {
files: ['src/**/*'],
// files: '<%= config.sourceFiles %>',
tasks: ['change'],
options: {
livereload: true,
spawn: false
}
}
});
// load the plugin that watches the connect tasks.
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.config('connect',{
local: {
options: {
port: 3335,
hostname: 'localhost',
livereload: true
}
}
});
//Load the plugin that lints my JavaScript
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.config('jshint',{
all: '<%= config.lintFiles %>',
options:{
curly: true,
immed: true,
newcap: true,
noarg: true,
sub: true,
boss: true,
eqnull: true
},
globals: {}
});
// Load the plugin that provides the concat tasks.
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.config('concat', {
dist:{
src: ['src/**/*.js'],
dest: 'build/concat.js',
}
});
// var allDependencies = [];
// for (var i = 0; i < pkg.dependencies.length; i++){
// console.log('i', i);
// }
console.log('1')
console.log('<%= pkg %>')
console.log('2')
// Load the plugin that provides the uglify tasks.
grunt.loadNpmTasks('grunt-contrib-uglify');
// defining my uglify task
grunt.config('uglify', {
options: {
banner: '/*\n* ©<%= pkg.author%>\n* <%= pkg.name %>\n* <%= grunt.template.today("yyyy-mm-dd HH:mm:ss") %> \n*/\n'
},
build: {
src: 'build/concat.js',
dest: 'build/<%= pkg.name %>-build.min.js'
}
});
// Default task(s).
var defaultTasks;
defaultTasks = ['lint', 'concat', 'uglify'];
var changeTasks;
changeTasks = ['lint', 'concat'];
var buildTasks = ['lint', 'concat', 'uglify'];
grunt.registerTask('change', changeTasks);
grunt.registerTask('server', ['connect:local', 'watch:all']);
grunt.registerTask('lint', ['jshint']);
grunt.registerTask('build', buildTasks);
grunt.registerTask('default', defaultTasks);
};
You'll notice that I have several DevDependancies that I don't want included in my production code. I tried finding a way to dynamically find all dependencies and add them to my concat path but I couldn't find a way. Any help would be wonderful.
Based off this answer: How to pass in package.json array to grunt.js
You should be able to read in the package.json file (and read it as a normal json object, right?). Then just access the attribute of dependencies, getting the name of each package.
I guess the hard part would be that each package has its own assets in different places that are not generally standard (or reliable enough to be standard). ie: angular/angular.min.js vs angular-ui-router/release/angular-ui-router.min.js (notice the addition of the folder 'release' inserted between).
This is just my initial impression, though.
I am trying to set up a workflow using grunt, to help with development of my jekyll site.
Found this great TUT which basically goes through how to install it in your workflow.
However, I get these errors when I run the 'grunt' command.
**[BS] Warning: Multiple External IP addresses found**
**[BS] If you have problems, you may need to manually set the 'host' option**
**[BS] Server running. Use this URL: http://192.168.1.5:3005**
[BS] Serving files from: /Users/antonioortiz/Sites/newaortiz/_site
**[BS] Not watching any files...**
[BS] Browser Connected! (Chrome, version: 33.0.1750.146)
Obviously the ones I bolded are most glaring, as NO css is being generated in my 'assets/css
Below is my Gruntfile. Thank you in advance.
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-jekyll');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-browser-sync');
// All configuration goes here
grunt.initConfig({
jekyll: {
build: {
dest: '_site'
}
},
sass: {
dist: {
files: {
'assets/css/*.css': 'assets/sass/*.scss'
}
}
},
compass: {
dev: {
options: {
config: 'config.rb'
} //options
} // dist
}, //compass
watch: {
sass: {
files: 'assets/**/*.scss',
tasks: ['sass']
},
jekyll: {
files: ['_layouts/*.html', '_includes/*.md', 'assets/css/*.css'],
tasks: ['jekyll']
}
},
compass: {
files: ['assets/sass/*.scss'],
tasks: ['compass:dev']
}, // sass
browser_sync: {
files: {
src: ['_site/assets/css/*.css']
},
options: {
watchTask: true,
ghostMode: {
clicks: true,
scroll: true,
links: true,
forms: true
},
server: {
baseDir: '_site'
}
}
}
});
// Custom tasks
grunt.registerTask('build', ['sass', 'jekyll']);
grunt.registerTask('default', ['build', 'browser_sync', 'watch']);
};