How to integrate Grunt with project from eclipse. - gruntjs

I am new to use grunt, please give the steps to integrate the grunt with dynamic web project (webcontent).

ok I will try to help you.
create a file called Gruntfile.js in the root of your project:
change the path according to your project.
module.exports = function(grunt) {
var config = {};
//src ===============================
var src;
config.src = src = {
sassMain: 'scss/main.scss',
distFolder: 'public/stylesheets/app.dist.css',
devFolder: 'public/stylesheets/app.dev.css',
sassFolder: 'scss/**/*.scss',
serverPort: 8000
};
//Concat ===============================
var concat
config.concat = concat = {};
concat.dev = {
files: {
"public/myapp.development.js": [
"with-bootstrap/public/js/vendor", "with-bootstrap/public/js/**/*.js"
]
}
};
//Watch ===============================
config.watch = {
scripts: {
files: ["<%= src.sassFolder %>"],
tasks: ["sass:dist"]
}
}
//Sass ===============================
var sass;
config.sass = sass = {};
//distribution
sass.dist = {
options: {
style: "compressed",
noCache: true,
sourcemap: 'none',
update: true
},
files: {
"<%= src.distFolder %>": "<%= src.sassMain %>"
}
};
//development env.
sass.dev = {
options: {
style: "expanded",
lineNumber: true,
},
files: {
"<%= src.devFolder %>": "<%= src.sassMain %>"
}
};
//grunt serve ===============================
config.connect = {
server: {
options: {
livereload: true,
port: "<%= src.serverPort %>"
}
}
};
//Register custom tasks ===============================
grunt.registerTask('default', ['dev']);
grunt.registerTask('dev', ['concat:dev', 'sass:dev']);
grunt.registerTask('dist', ['concat:dev', 'sass:dist']);
grunt.registerTask('serve', ['connect:server', 'watch']);
require('time-grunt')(grunt);
require('load-grunt-tasks')(grunt, {
scope: 'devDependencies'
});
//General setup ===============================
grunt.initConfig(config);
};
in the root of your project run: npm init fill out with the info of your project.
after this open the package.json file, we are now will include the grunt tasks to be installed.
"devDependencies": {
"grunt": "*",
"grunt-contrib-concat": "*",
"grunt-contrib-connect": "^1.0.2",
"grunt-contrib-sass": "*",
"grunt-contrib-watch": "*",
"grunt-exec": "^1.0.1",
"load-grunt-tasks": "^3.5.0",
"time-grunt": "^1.3.0",
"express": "^4.14.0"
}
run npm install to install the grunt tasks and npm dependencies.
be aware you need have installed in your computer grunt and npm.
anyway let me know if that helped you.
good luck

Related

Browsersync on my port 10080

I can't get Grunt's browser sync to update my changes. I have not use Grunt much so I am a bit new to this. Maybe some of you know what could be wrong?
I am using XAMPP and runs a wordpress site at:
http://localhost:10080/wp_demo2/
(I use port 10080 to avoid conflict with Skype)
Here is my gruntfile.js (updated)
var root = './htdocs/wp_demo2/wp-content/themes/isak/';
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
options: {
style: 'expanded',
precision: 5
},
all: {
files: {
'css/output.css': 'scss/input.scss'
}
}
},
watch: {
files: 'scss/**/*.scss',
tasks: ['sass']
},
browserSync: {
dev: {
bsFiles:
{
src: [root+'css/output.css', root + '**/*.php']
},
options: {
watchTask: true,
proxy: "localhost:10080/wp_demo2"
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-browser-sync');
grunt.registerTask('default', ['browserSync', 'watch']);
};
files inside Browsersync's options is a local path, not a URL. I would set port in the path and move the routes to the files outside options.
// ...
browserSync: {
dev: {
bsFiles: {
src: ['css/output.css', '**/*.php']
},
options: {
watchTask: true,
proxy: 'localhost:10080/wp_demo2'
}
}
}
// ...
grunt.registerTask('dev', ['sass', 'browserSync', 'watch']);
Browsersync should update when output.css is modified.
Your Gruntfile.js should be located in . path.
**/* means "search in all folders".

How to create standalone bundle of React & React with Addons using Grunt + Browserify?

I am trying to configure Grunt & Browserify to output a standalone bundle containing, among other things, React as CommonJS module so that it can be referenced by other bundles.
The problem that I am having now is that the aliasing does not seem to work. Despite having specified aliases in my external bundle vendor below, and having specified that those modules should be loaded externally in all the other models, I'm still getting an error at run time, stating that the 'react' module cannot be found.
It would be great if anyone knows what might be wrong about my grunt-browserify syntax here:
var externals = [
'react',
'react/addons',
'jquery',
'backbone',
'react-router'
];
module.exports = function(grunt) {
grunt.config.set('browserify', {
main: {
src: 'assets/js/main.jsx',
dest: '.tmp/public/js/main.js',
options: {
debug: true,
extensions: ['.jsx'],
external: externals,
transform: [
['babelify', {'stage': 0}]
]
}
},
signup: {
src: 'assets/js/signup.jsx',
dest: '.tmp/public/js/signup.js',
options: {
debug: true,
extensions: ['.jsx'],
external: externals,
transform: [
['babelify', {'stage': 0}]
]
}
},
login: {
src: 'assets/js/login.jsx',
dest: '.tmp/public/js/login.js',
options: {
debug: true,
insertGlobals: true,
extensions: ['.jsx'],
external: externals,
transform: [
['babelify', {'stage': 0}]
]
}
},
vendor: {
src: [
'./node_modules/react/dist/react.js',
'./node_modules/react/dist/react-with-addons.js',
'./node_modules/jquery/dist/jquery.js',
'./node_modules/backbone/backbone.js',
],
dest: '.tmp/public/js/dependencies/vendor.js',
options: {
debug: false,
alias: {
'react:': './node_modules/react/dist/react.js',
'react/addons': './node_modules/react/dist/react-with-addons.js',
'jquery': './node_modules/jquery/dist/jquery.js',
'backbone': './node_modules/backbone/backbone.js',
'react-router': './node_modules/react-router/lib/index.js'
},
shim: {
react_router: {
path: './node_modules/react-router/lib/index.js',
exports: 'react-router'
}
},
external: null
}
}
});
grunt.loadNpmTasks('grunt-browserify');
};
I've found this link helpful for me. Following this approach your vendor section should look like
vendor: {
src: ['.'],
dest: '.tmp/public/js/dependencies/vendor.js',
options: {
debug: false,
alias: externals.map(function(module) {
return module + ':';
}),
shim: {
react_router: {
path: './node_modules/react-router/lib/index.js',
exports: 'react-router'
}
},
external: null
}
}
I'm not sure about the shim section above, because I've tried this only for the react module.
I am working on a Sails 0.11.0 project with ReactJS. I start my grunt watchify task to handle rebundling/transforming my app code, while using the vendor task to bundle the moduled code. I additionally had to add the vendor.js to my layout file.
I am fairly new to the grunt world, so there may be more efficient ways to do this.
browserify.js
var externals = [
'react',
'react/addons',
'jquery',
'react-router',
'events'
]
module.exports = function(grunt){
grunt.config.set('browserify', {
dist: {
options: {
external: externals,
transform: [
['babelify', {
loose: 'all'
}]
]
},
files: {
".tmp/public/js/bundle.js": ["assets/js/bundle.js", "react/**/*"]
}
},
vendor: {
src: [
'./node_modules/react/dist/react.js',
'./node_modules/react/dist/react-with-addons.js',
'./node_modules/jquery/dist/jquery.js',
'./node_modules/react-router/lib/index.js',
'./node_modules/events/events.js'
],
dest: '.tmp/public/js/dependencies/vendor.js',
options: {
alias: {
'react': './node_modules/react/dist/react.js',
'react/addons': './node_modules/react/dist/react-with-addons.js',
'jquery': './node_modules/jquery/dist/jquery.js',
'react-router': './node_modules/react-router/lib/index.js',
'events': './node_modules/events/events.js'
}
}
}
});
grunt.loadNpmTasks('grunt-browserify');
}
tasks/config:
module.exports = function(grunt) {
grunt.config.set('watch', {
api: {
// API files to watch:
files: ['api/**/*', '!**/node_modules/**']
},
assets: {
// Assets to watch:
files: ['assets/**/*', 'tasks/pipeline.js', '!**/node_modules/**'],
// When assets are changed:
tasks: ['syncAssets' , 'linkAssets', 'browserify:dist']
},
react: {
files: ['react/**/*'],
tasks: ['browserify:dist']
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
};
Here is the full Grunt configuration for the React:
https://github.com/koshkarov/reactjs-grunt-configuration
I've created a dummy project so you can build it to test.
Gruntfile.js for the project:
module.exports = function (grunt) {
let concat = {};
let clean = {};
let uglify = {};
let copy = {};
let htmlmin = {};
let cssmin = {};
let browserify = {};
let watch = {};
let template = {};
let run = {};
/* React configuration. */
const reactSourcePath = './source';
const reactCompiledPath = './client';
const reactHtmlPathDest = './client/index.html'
const reactTargetName = "react";
const reactFileName = "react_main";
/* ### TASK CONFIGURATIONS ### */
/* Clean compiled files. */
clean[reactTargetName] = [
`${reactCompiledPath}`
];
/* Concatenate all CSS files to one. */
const cssConcatSourceTemplate = `${reactSourcePath}/**/**.css`;
const cssDestinationFile = `${reactCompiledPath}/css/${reactFileName}.css`;
concat[reactTargetName] = {
src: [cssConcatSourceTemplate],
dest: cssDestinationFile
};
/* Convert JSX to JS, prepare JS files for a browser and copy to the destination. */
const jsSourceFile = `${reactSourcePath}/index.js`;
const jsDestinationFile = `${reactCompiledPath}/js/${reactFileName}.js`;
browserify[reactTargetName] = {
options: {
transform: [['babelify', {presets: ['es2015', 'react']}]]
},
files: {
[jsDestinationFile]: jsSourceFile
}
};
/* Replace js/css placeholders and copy html file to destination. */
const applicationData = {
css: [
'./css/react_main.css'
],
js: [
'./js/react_main.js'
]
};
var jsFiles = "";
var cssFiles = "";
applicationData.css.forEach(function(item) {
cssFiles = cssFiles + `\n<link rel="stylesheet" type="text/css" href=${item}>`;
});
applicationData.js.forEach(function(item) {
jsFiles = jsFiles + `\n<script type="text/javascript" src=${item}></script>`;
});
template[reactTargetName] = {
options: {
data: {
appName: '<%= pkg.name %>' + '-react',
productVersion: '<%= pkg.version %>',
reactEmbeddedCssFiles: cssFiles,
reactEmbeddedJsFiles: jsFiles
}
},
files: {
[`${reactHtmlPathDest}`]: `${reactSourcePath}/index.template.html`,
}
};
/* Uglify react JS file. */
uglify[reactTargetName] = {
files: {
[jsDestinationFile]: jsDestinationFile
}
};
/* Copy bootstrap CSS/JS files. */
copy[reactTargetName] = {
files: {
[`${reactCompiledPath}/css/bootstrap.min.css`]: 'node_modules/bootstrap/dist/css/bootstrap.min.css',
[`${reactCompiledPath}/js/bootstrap.min.js`]: 'node_modules/bootstrap/dist/js/bootstrap.min.js',
[`${reactCompiledPath}/js/jquery.min.js`]: 'node_modules/jquery/dist/jquery.min.js',
}
}
/* Minify HTML files. */
htmlmin[reactTargetName] = {
options: {
removeComments: true,
collapseWhitespace: true
},
files: {
[`${reactHtmlPathDest}`]: `${reactHtmlPathDest}`
}
};
/* Minify react CSS file. */
cssmin[reactTargetName] = {
files: {
[cssDestinationFile]: cssDestinationFile
}
};
/* Watch for any changes in react app.
There are three separate watches for css, js, and html files. */
watch[reactTargetName + '_css'] = {
files: [`${reactSourcePath}/**/*.css`],
tasks: [`concat:${reactTargetName}`],
options: {
livereload: true
}
};
watch[reactTargetName + '_js'] = {
files: [`${reactSourcePath}/**/*.js`],
tasks: [`browserify:${reactTargetName}`],
options: {
livereload: true
}
};
watch[reactTargetName + '_hmtl'] = {
files: [`${reactSourcePath}/**/*.html`],
tasks: [`template:${reactTargetName}`],
options: {
livereload: true
}
};
/* Jest tests */
jestTestsTaskName = reactTargetName + '_jest_tests';
run[jestTestsTaskName] = {
exec: 'npm test'
};
/* Generate task names for react. */
var reactTasks = {
debug: [
"clean",
"browserify",
"concat",
"copy",
"template"
].map(x => x + `:${reactTargetName}`),
release: [
"clean",
"browserify",
"concat",
"copy",
"template",
"htmlmin",
"uglify",
"cssmin"
].map(x => x + `:${reactTargetName}`)
};
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch:watch,
copy:copy,
concat:concat,
clean:clean,
uglify:uglify,
template:template,
browserify: browserify,
htmlmin: htmlmin,
cssmin: cssmin,
run:run
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-template');
grunt.loadNpmTasks("grunt-browserify");
grunt.loadNpmTasks("grunt-contrib-htmlmin");
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-run');
grunt.registerTask('react_build_debug', reactTasks.debug);
grunt.registerTask('react_build_release', reactTasks.release);
}

Getting grunt to build a single javascript file containing all dependencies (reading from node_modules)

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.

Why can't I get 'grunt-browser-sync' to work with jekyll?

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']);
};

Grunt livereload not working

I'm quite new to grunt, and I'm trying to enable livereload.
The problem is that I can't seem to get it working.
Gruntfile.js:
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> */'
},
my_target: {
files: {
'dest/complete.min.js': ['scripts/*.js']
}
}
},
jshint: {
files: ['gruntfile.js', 'srcipts/*.js'],
options: {
// options here to override JSHint defaults
globals: {
jQuery: true,
console: true,
module: true,
document: true
}
}
},
livereload : {
options : {
base : '/',
},
files : ['/**/*']
},
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-livereload');
grunt.registerTask('default', ['jshint', 'uglify','livereload']);
};
package.json:
{
"name": "my-app",
"version": "0.0.0",
"devDependencies": {
"grunt": "~0.4.1",
"grunt-contrib-uglify": "~0.2.0",
"grunt-contrib-jshint": "~0.6.0",
"grunt-contrib-livereload": "0.1.2",
"matchdep": "~0.1.2"
}
}
I don't get any errors,
I've tried: "grunt" and "grunt livereaload-start".
When going to my website via localhost - it won't connect.
And viewing the website via the file:// protocol will not reload when changes are made to css files.
Thanks in advance.
Live reloading has been moved to the watch task. Please see: https://github.com/gruntjs/grunt-contrib-watch#live-reloading
grunt.initConfig({
watch: {
livereload: {
options: { livereload: true },
files: ['dist/**/*'],
},
},
});

Resources