How to run multiple Grunt scripts in the background together? - javascript

grunt.registerTask('dev', ['browserSync:dev', 'webpack', 'watch']);
this is my Grunt-Dev script that I need running while developing. It is run to do three things.
1) Watch SCSS files for changes then compile them to CSS (watch + sass)
2) Start a liveserver with BrowserSync which has reloading built in
3) Run a webpack script that watches for changes to js files, and recompiles them into a bundle.js whenever there are changes
All of these work, however, I do not want to have three command prompts open every time and have to type out each command. Instead, having them all run with one grunt script is the goal
its 75% working. I can have SASS/watch + BrowserSync going at the same time with
grunt.registerTask('dev', ['browserSync:dev', 'watch']);
This works because BrowserSync has a watchtask: true option which means that it will run "in the background". But adding in the third script (webpack) I would need either watch or webpack to have an option like that as well. Because right now, no matter where I place webpack script, either it or the watch scrip will act as a wall for other scripts to run
here is the full Grunt scripts for reference
webpack: {
myconfig: function() {
return {
entry: './app/src/js/App.jsx',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'app/src')
},
watch: true,
mode: 'production',
devtool: "source-map"
};
}
},
browserSync: {
dev : {
bsFiles: {
src : ['app/**/*', '!app/src/js/*.js', '!**/*.scss']
},
options: {
server: {
baseDir: "./app"
},
watchTask: true,
notify: false
}
}
},
sass: {
dist: {
options:{
},
files: [{
expand: true,
cwd: 'app/scss',
src: ['theme.scss'],
dest: 'app/',
ext: '.css'
}]
}
},
watch: {
scripts: {
files: '**/*.scss',
tasks: ['sass'],
options: {
spawn: false
},
},
},

Related

How to get Javascript Const to work with Grunt Uglify?

I am trying to use javascript Const with Grunt Uglify but receive the error:
Unexpected token: keyword «const».
I have done a little googling and tried
npm install terser-webpack-plugin --save-dev
However that did not work.
It was stated I needed to add the following to my Plugins array...
const TerserPlugin = require('terser-webpack-plugin')
new TerserPlugin({
parallel: true,
terserOptions: {
ecma: 6,
},
}),
I wasn't sure exactly where to add this though? Does it go in my grunt file.js?
Additionally I also saw that a fix might be to use the harmony branch of grunt-contrib-uglify. But I fear this method is out of date?
Ultimately I am attempting to code a cookie consent pop up. Does anyone know how to get Const to work with grunt uglify?
Or does anyone have a better recommendation for coding cookie consent pop ups?
Many thanks.
Edit: Adding grunt file as requested
// Load Grunt
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Tasks
sass: { // Begin Sass Plugin (this takes all your scss files and compiles them into style.css)
dist: {
files: [{
expand: true,
cwd: 'assets/scss/my-theme',
src: ['**/*.scss'],
dest: 'dist/css',
ext: '.css'
}]
}
},
postcss: { // Begin Post CSS Plugin (this applies browser prefixes to your compiled style.css in 'dist' folder)
options: {
map: false,
processors: [
require('autoprefixer')({
overrideBrowserslist: ['last 2 versions']
})
]
},
dist: {
src: 'dist/css/style.css'
}
},
cssmin: { // Begin CSS Minify Plugin (this takes your style.css file from 'dist', minifies it and creates style.min.css)
target: {
files: [{
expand: true,
cwd: 'dist/css',
src: ['style.css', '!*.min.css'],
dest: 'dist/css',
ext: '.min.css'
}]
}
},
uglify: { // Begin JS Uglify Plugin (this takes your my-theme js files in 'assets', minifies them and creates script.min.js in 'dist' folder)
build: {
src: ['assets/js/my-theme/*.js'],
dest: 'dist/js/script.min.js'
}
},
watch: { // Compile everything into one task with Watch Plugin (this watches for any changes to scss and js files, so make sure it is pointing to your 'my-theme' CSS and JS folders in 'assets')
css: {
files: 'assets/scss/my-theme/**/*.scss',
tasks: ['sass', 'postcss', 'cssmin']
},
js: {
files: 'assets/js/my-theme/**/*.js',
tasks: ['uglify']
}
}
});
// Load Grunt plugins
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-postcss');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-terser');
// Register Grunt tasks
grunt.registerTask('default', ['watch']);
};

Most of Grunt tasks are not found

This is my first day with grunt and I'm trying to make it work using these tutorials
https://24ways.org/2013/grunt-is-not-weird-and-hard/
https://css-tricks.com/autoprefixer/
And my Gruntfile.js is this:
module.exports = function(grunt) {
// 1. All configuration goes here
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
scripts: {
files: ['scripts/app.js'],
tasks: ['uglify'],
options: {
spawn: false,
}//For some reason I had a come here. Don't know if it matters
},
css: {
files: ['content/app.scss'],
tasks: ['sass'],
options: {
spawn: false,
}
},
styles: {
files: ['content/app.css'],
tasks: ['autoprefixer']
}
},
uglify: {
build: {
src: "scripts/app.js",
dest: "scripts/app-final.js"
}
},
sass: {
dist: {
options: {
style: 'compressed'
},
files: {
'content/app.css': 'content/app.scss'
}
}
},
autoprefixer: {
dist: {
files: {
'content/app-prefixed.css': 'content/app.css'
}
}
},
imagemin: {
dynamic: {
files: [{
expand: true,
cwd: 'assets/img/',
src: ['**/*.{png,jpg,gif}'],
dest: 'assets/img/'
}]
}
}
});
// 3. Where we tell Grunt we plan to use this plug-in.
grunt.loadNpmTasks(
'grunt-contrib-uglify',
'grunt-contrib-sass',
'grunt-autoprefixer',
'grunt-contrib-watch',
'grunt-contrib-imagemin'
);
// 4. Where we tell Grunt what to do when we type "grunt" into the terminal.
grunt.registerTask(
'default', [
'watch',
'uglify',
'sass',
'autoprefixer',
'imagemin'
]);
};
But when I try grunt watch watch I get this:
# grunt watch
Warning: Task "watch" not found. Use --force to continue.
Aborted due to warnings.
To make things weirder grunt uglify is seen
# grunt uglify
Running "uglify:build" (uglify) task
>> Destination scripts/app-final.js not written because src files were empty.
>> No files created.
Done, without errors.
Running grunt --help gives me an interesting thing
Available tasks
uglify Minify files with UglifyJS. *
default Alias for "watch", "uglify", "sass", "autoprefixer", "imagemin" tasks.
I really cannot find a difference between uglify and the other functions. VS Code doesn't give me any errors. I installed all of the used tasks. I have node installed.
Restarting VS Code doesn't help. I don't think this matters but just in case, I'm using Linux.
Reinstalling the dependencies didn't help either
You did the following:
grunt.loadNpmTasks(
'grunt-contrib-uglify',
'grunt-contrib-sass',
'grunt-autoprefixer',
'grunt-contrib-watch',
'grunt-contrib-imagemin'
);
Replace it with this:
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-uglify');
Grunt does not take multiple Arguments in grunt.loadNpmTasks for some reason. You can see the proper usage of the loadNpmTasks - function in the documentation: https://gruntjs.com/sample-gruntfile

Grunt Sass - Multiple css style outputs

I've done a fair bit of searching but can't seem to come up with a full answer to this.
I'm using grunt to manage my sass flow and I've been trying to find a way to output multiple css styles from grunt.
For example:
base.scss should have two outputs the first being style.css which has the expanded css style.
The second should be style.min.css which has the compressed css style.
How can I configure my gruntfile to do this for me?
You can do this by having two configurations, one outputting expanded CSS and the other compressed. Then register your task to run both. Your grunt file should look something like this:
Example
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Sass
sass: {
dev: { // This outputs the expanded css file
files: {
'style.css': 'base.scss'
}
},
prod: { // This outputs the compressed css file
options: {
outputStyle: 'compressed' // Minify output
},
files: {
'style.min.css': 'base.scss'
}
}
}
});
grunt.registerTask('default', ['sass:dev', 'sass:prod']); // Task runs both
}
Here is a more complete solution of what belongs in gruntfile.js, improving upon what Colin Bacon has already posted. By default grunt's pkg is already set to read package.json in the current directory, so no need to write that. You just need to install the jit-grunt plugin (besides the watch and sass plugins of course) to get my answer working.
module.exports = function(grunt) {
require('jit-grunt')(grunt);
grunt.initConfig({
sass: {
expanded: { // Target
options: { // Target options
style: 'expanded'
},
files: { // Dictionary of files
'style.css': 'style.scss' // 'destination': 'source'
}
},
compressed: { // Target
options: { // Target options
style: 'compressed'
},
files: { // Dictionary of files
'style.min.css': 'style.scss' // 'destination': 'source'
}
}
},
watch: {
styles: {
files: ['**/*.scss'], // which files to watch
tasks: ['sass'],
options: {
spawn: false // speeds up watch reaction
}
}
}
});
grunt.registerTask('default', ['sass', 'watch']);
};
Just add a new manifest file in your styles folder. For example, you have normally main.scss, if you create main2.scss and import some files in there. It will create a file for each manifest file you have.
If your sass task looks something like this (default yeoman webapp generator):
sass: {
options: {
sourceMap: true,
includePaths: ['bower_components']
},
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/styles',
src: ['*.{scss,sass}'],
dest: '.tmp/styles',
ext: '.css'
}]
},
server: {
files: [{
expand: true,
cwd: '<%= config.app %>/styles',
src: ['*.{scss,sass}'],
dest: '.tmp/styles',
ext: '.css'
}]
}
}
The file section sass read all .scss/.sass files and copy those to .tmp/styles. Later, copy task move those to dist/styles.

Using Grunt Serve to show website on localhost?

I've built Gruntfiles in the past, but mostly to compile Less and Jade, so this steps a bit out of my comfort zone and I'm struggling to figure out what to do.
I'd like to use the Gruntfile to:
Compile Jade to html
Compile Less to css
Build and show website at localhost:9000
Refresh localhost:9000 upon save of file (this uses grunt watch I'm assuming?)
Basically, I'd like to keep it light and easy, so that once I learn I can use it to teach others that I know. :)
Here's what my Gruntfile looks like so far. I have grunt-serve in there, but nothing loads to the page when I run it, so I'm really confused. Thanks for the help!
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-jade');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
jade: {
compile: {
options: {
client: false,
pretty: true
},
files: [ {
cwd: "assets/views",
src: "**/*.jade",
dest: "public",
expand: true,
ext: ".html"
} ]
}
},
less: {
development: {
options: {
compress: true,
yuicompress: true,
optimization: 2
},
files: {
// target.css file: source.less file
'public/css/main.css': 'assets/less/main.less',
}
}
},
watch: {
styles: {
files: [
'less/main.less',
],
tasks: ['less'],
options: {
nospawn: true
}
}
},
serve: {
options: {
port: 9000
}
}
});
grunt.registerTask('default', ['jade','less']);
grunt.loadNpmTasks('grunt-serve');
};
I think your build task is running jade and less, but not serve. Instead of
grunt.registerTask('default', ['jade','less']);
try
grunt.registerTask('default', ['jade','less','serve']);

Grunt Livereload not showing HTML changes

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 :)

Categories

Resources