Grunt-newer with Grunt-uglify and Bower - gruntjs

I've got a project using Grunt and Bower. Grunt-uglify will concatenate/minify files from the Bower directory to the deploy/scripts.js folder. I'm using Grunt-newer so it will only update deploy/scripts.js if new files are added or changed. Everything works great...except...
When I add a new library with Bower, file date reflects when the file was uploaded to the Bower library (or whoever is hosting it), not the date it was create on my computer. Thus, Grunt-newer sees the new Bower libraries are being older than deploy/scripts.js and does not update the file.
One--cumbersome--solution is to open the new library .js file, and resave it. It modifies the file dates and thus, grunt-newer will create the deploy/script.js file. However, the usefulness of Bower seems moot with such an awkward solution.

You can use Bower hooks in order to manipulate the files modification time. This is kind of a hack but can achieve what you are looking for.
You will need to register a postinstall hook and pass the list of updated components as an argument. When the script is called, the % will be replaced with a space-separated list of components being installed or uninstalled.
The hooks should be registered in the .bowerrc file:
{
"scripts": {
"postinstall": "hook.sh %"
}
}
Then you will need a script which iterates over the components and changes the modification time of the files.
For example a shell script:
#!/bin/bash
for var in "$#"
do
find "./bower_components/$var" -exec touch {} \;
done
Here is another example of a node.js script for the same purpose:
var fs = require('fs');
var path = require('path')
var components = process.argv.slice(2)
components.forEach(function (comp) {
var comp_path = path.join(process.cwd(),"bower_components",comp);
var files = fs.readdirSync(comp_path);
files.forEach(function(file) {
fs.utimesSync(path.join(comp_path, file), new Date(), new Date());
});
});

Related

How use bootstrap-sass efficiently?

I'm currently discovering modules with npm, and I went to use bootstrap-sass. Now that the modules were downloaded, I was looking for a solution to compile scss into the static folder of the application, and also the js bootstrap files.
But according to npmjs documentation of the modules, I can't found a simple solution which is not to move the js files myself and compile the scss bootstrap files from node_modules with something like node-sass.
What is the simplest way to use this module correctly and with the possibility to custom ?
Edit :
For now, I am using the following scripts/files :
"compile-js": "browserify assets/static/js/main.js | uglifyjs > assets/static/js/bundle.js",
"compile-sass": "node-sass assets/scss/app.scss assets/static/css/app.css --output-style compressed"
app.scss
#import "../../node_modules/bootstrap-sass/assets/stylesheets/_bootstrap-sprockets.scss";
#import "../../node_modules/bootstrap-sass/assets/stylesheets/_bootstrap.scss";
main.js
global.jQuery = require("jquery")
const bootstrap = require('bootstrap-sass');
I've never used bootstrap-sass before, but the documentation implies that a build tool to preprocess the SCSS is a prerequisite for using this module. While it's no longer the shiniest tool in the shed, Gulp is very capable of handling this task as well as moving the files from node_modules to your project root directory for you.
Here's a breakdown of one approach to implement this:
Create three subfolders in your project root directory and call them sass, css and javascript.
Create a file in the sass folder and call it app.scss. Open it and paste this: #import './node_modules/bootstrap-sass/assets/stylesheets/_bootstrap.scss';. When the file is converted into CSS, all of the Bootstrap modules will be there. Beneath the #import statement on line 1, feel free to write whatever style rules you want.
Assuming you have already run npm init and have a package.json file in your project directory, run npm install gulp -D in your terminal. This installs gulp (my task runner of choice!).
Run npm install gulp-sass --save-dev. This installs the gulp plugin that will preprocess the Bootstrap SASS into CSS.
Create a file in your root directory (not in any of the subfolders) called gulpfile.js
Copy and paste this text into gulpfile.js:
(note: for this to work, your SASS and CSS folders must be called sass and css, respectively, unless you change their names in the following code.)
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass-to-css', function () {
return gulp.src('./sass/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
gulp.task('javascript', function () {
return gulp.src('./node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js')
.pipe(gulp.dest('./javascript'));
});
gulp.task('default', ['sass-to-css', 'javascript']);
Lastly, run the command gulp in your terminal to execute the gulpfile, which will do two things:
Preprocess and move all of the SASS into your css folder.
Copy bootstrap.min.js from node_modules into your project's javascript folder.
Of course, don't forget to link to these assets in your HTML.
I whipped up this gulpfile on the fly and it works on my machine, but if you decide to try this approach then feel free to ask if something throws an error. Best of luck on your project.

How to use Laravel 5 with Gulp, Elixir and Bower?

I am completely new to all this, 'Bower' and 'Gulp' and Laravel 'Elixir'. I purchased a template that uses them (unfortunately) and now I need some help on how to go about implementing them. I have already installed NPM and Bower. All my packages have been downloaded into:
resources > assets > vendor
This is a screenshot:
Now my question is how do I include all those packages I downloaded in my view? From my understanding I can't run less files directly in the browser, it only runs once due to 'browser caching' or something like that, also the JS scripts are just too many to include in my page.
I want a way where I can work on my files and have them automatically compiled with the compiled files being referenced in my app.php file.
This is a link to the GulpJS file included in my template: http://pastebin.com/3PSN6NZY
You do not need to compile every time someone visits. The compiled sass/js should be run in dev and then the output files referenced.
If you have gulp installed on the project, you should see a gulp.js file in the root of your project. If not, visit here for instructions:
Gulp/Elixer installation and setup
In your gulp.js file:
var elixir = require('laravel-elixir');
elixir(function(mix) {
mix.less([
'app.less',
'normalize.less',
'some-other-less.less',
'and-another.less'
]);
mix.scripts(['app.js', 'some-other-js.js'], 'public/js/output-file.js');
});
While in development you can run gulp watch from the command line to listen for changes and run compile tasks when it hears a change. Then you simply reference the output files in the public directory as you normally would.
If you don't want to listen, you can just run the gulp command for a single once-off task run.
The docs are pretty straight forward and can be found here:
Gulp/Elixer docs

Visual Studio: Handling Typescript and LESS project files (with TFS Build)

I currently have an ASP.Net MVC project setup that uses .less files and standard .js files.
My less files get compiled when they're saved by the Web Essentials Visual Studio extension, and appear like so:
One annoying thing I have to do is set the less file's Build Action to 'None' so it doesn't end up in the built files on the server, but that's manageable.
I've added the TypeScript extension to Visual Studio, and I'm starting to convert my .js files over to .ts files. Similar to the .less files, they will be recompiled when I save the .ts file; however, the .js file is not added to my project. This is an issue since TFS won't have the .js file for its build (and won't compile the file, since that TypeScript tool doesn't exist there).
I can add the .js file to the project, and then hack the project file to make it a dependency:
However, this process also seems like a bit of a pain. So to my question: What is the correct approach I should be taking here?
1) Do not include .css and .js files in TFS, and find a way to have our TFS server compile these during build (add the .ts extension somehow, and is there a build action for compiling .less?).
2) Include all files like I'm currently doing, but find a better way of adding .ts files (without editing the project file) and .less files (without needing to change the build action).
So far I haven't been able to find a good solution for either route.
Go with option 1. Only commit the Less and Typescript files and let the build system generate the css and Javascript.
Since asking this question, we've upgraded to Visual Studio 2015 and left TFS for Atlassian, but this should still be applicable:
I deleted all generated css files and added the following gulpfile.js to the project:
/// <binding AfterBuild='less' ProjectOpened='less-watch' />
var gulp = require('gulp');
var less = require('gulp-less');
var watch = require('gulp-watch');
var path = require('path');
var plumber = require('gulp-plumber');
var concat = require('gulp-concat');
var lessPaths = [*my file paths*];
gulp.task('less', function () {
return gulp.src(lessPaths, { base: "./" })
.pipe(plumber())
.pipe(less())
.pipe(concat('app-styles.css'))
.pipe(gulp.dest('./styles/'));
});
gulp.task('less-watch', function () {
gulp.watch(lessPaths, ['less']);
});
This concats all of my generated files into a '/styles/app-styles.css' file. From there, we need to add the following to the .csproj file to get this new file copied into our output folder on build/deploy:
<Target Name="GulpTasks" AfterTargets="AfterBuild">
<Exec Command="npm install" />
<Exec Command="node_modules\.bin\gulp less" />
<Copy SourceFiles="styles\app-styles.css" DestinationFolder="$(WebProjectOutputDir)\styles" />
</Target>

How to tell Meteor to ignore `gulpfile.js`

In my meteor project I want to use gulp for tasks meteor doesn't support.
Anyway, the problem is that gulp uses a file called gulpfile.js which is loaded by meteor too and gives errors. So my question is, is there a way to tell meteor to ignore some files ?
UPDATE: One solution I can think of is to put gulpfile.js in the folder packages or public and run gulp as follows
$> gulp --gulpfile packages/gulpfile.js
UPDATE: Just noticed that meteor also seems to load node_modules files :(
Unfortunately, in the current release there's no way to tell Meteor to leave certain files alone, so you cannot have gulpfile.js in your main app folder.
You can, however, leave it in an ignored subfolder. Meteor ignores files and directories that ends with tilde ~, the /tests directory and all private files (those beginning with a dot .). So you can create a folder named for example gulp~ and use it for your gulp-related stuff.
The same holds for node_modules folder, you cannot have it in your application, and you shouldn't. If you want to use a node package in your Meteor application, you can do this with npm package.
Add it to your project with mrt add npm command.
Then create packages.json file with a list of all required packages, for example:
{
"something": "1.5.0",
"something-else": "0.9.11"
}
Afterwards, include your package with Meteor.require:
var something = Meteor.require('something');
If you want to use a node package in your gulp tasks, install it inside the ignored directory.

Setting up auto compile for Stylus

I have installed node.js/stylus/nib on my mac and I can manually compile .styl file to .css on the command line. I also know there is this stylus.middleware() things that keeps coming up when I search for how to setup auto-compiling when the .styl changes, however I have no idea how I am supposed to implement it (I have never used node.js before).
What file do I put that code in?
How do I start this code so it is always run?
I think I am missing a few things on the node side to be able to set this up.
From the command line you can use:
stylus -w folder/
or just for another example:
stylus -w styl/*.styl -o css/
It will watch for changes and compile all *.styl files that live under that folder.
If you installed stylus as a global package (npm install stylus -g) you have a stylus binary on your system.
$ stylus -h
Usage: stylus [options] [command] [< in [> out]]
[file|dir ...]
Commands:
help [<type>:]<prop> Opens help info at MDC for <prop> in
your default browser. Optionally
searches other resources of <type>:
safari opera w3c ms caniuse quirksmode
Options:
-i, --interactive Start interactive REPL
-u, --use <path> Utilize the stylus plugin at <path>
-U, --inline Utilize image inlining via data uri support
-w, --watch Watch file(s) for changes and re-compile
-o, --out <dir> Output to <dir> when passing files
-C, --css <src> [dest] Convert css input to stylus
-I, --include <path> Add <path> to lookup paths
-c, --compress Compress css output
-d, --compare Display input along with output
-f, --firebug Emits debug infos in the generated css that
can be used by the FireStylus Firebug plugin
-l, --line-numbers Emits comments in the generated css
indicating the corresponding stylus line
--include-css Include regular css on #import
-V, --version Display the version of stylus
-h, --help Display help information
This briefly covers some Node basics.
0. Organizing code. It is a convention to put your main Node application code into a file called app.js in the project root.
Inside app.js things are grouped into two general parts:
synchronous initializations: require modules, build directories, read configs, db connections, etc. Things that block, so they must exist or die quickly.
asynchronous app tasks: start server, background processes, auto-compile CSS & JS, routing, i/o, etc. Things that are in the event loop.
1. Compile Stylus to CSS when you build the app. We need to require the stylus module. Usually this is done at the top of the app.js to keep dependencies together.
var stylus = require('stylus');
The first time that Node runs app.js, you need this JS module to build your CSS. This is the basic idea:
stylus.render(stylus-code-string, function(err, css) {
if (err) throw err;
console.log(css);
});
Here is the official Stylus Javascript API.
To use the power of Node, you should read a stylus file using fs module into a buffer, then convert it to a string, and finally pass it into stylus.render(). Then, send the result into a destination file. Since this is part of the build process, it can be synchronous. But this is not really your question...
2. Auto-compile CSS with Stylus as a background process.
This function spawns a child_process that watches a single .styl file and compiles the included .styl files into a .css file. You do not need a module for this, only install the stylus executable so that it runs on the command line. (You have already done this). This example was made with stylus version 0.5.0. Also, the folder paths that you use (ex. build/styles and styles) need to exist.
function watchStyles(sourcefile, destinationfolder) {
var Stylus = child_process.spawn('stylus', ['--sourcemap', '-w', sourcefile, '--out', destinationfolder]);
Stylus.stdout.pipe(process.stdout); // notifications: watching, compiled, generated.
Stylus.stderr.pipe(process.stdout); // warnings: ParseError.
Stylus.on('error', function(err) {
console.log("Stylus process("+Stylus.pid+") error: "+err);
console.log(err);
});
// Report unclean exit.
Stylus.on('close', function (code) {
if (code !== 0) {
console.log("Stylus process("+Stylus.pid+") exited with code " + code);
}
});
}
Next, you need to call this function sometime after you start your app. Pass in your master .styl file as the source. Then the destination directory where you want your CSS to go.
// check that you passed '-w' parameter
if (process.argv[2] && (process.argv[2] == "-w")) {
watchStyles('styles/app.styl', 'build/styles');
}
Start the app by running:
$ node app.js -w
It helps to organize your .styl files under one app.styl so that the contents of your app.styl looks like this:
#import 'layout'
#import 'header'
#import 'main'
#import 'footer'
#import 'modal'
#import 'overrides'
** I end up here yesterday and didn't find the right answer. So this follow up is for anyone else who follows the same path as me... **
I had a problem setting stylus command line up too. I kept trying to install stylus globally
$ npm install -g stylus
and would get errors. I had it working in one project with grunt-contrib-stylus but via command line I wasn't getting anything to work.
Even $stylus --version didn't return anything. I tried to update npm and it broke npm, so I ended up reinstalling node to reinstall npm. Then I was able to do a fresh install of $ sudo npm install -g stylus and could get the --version.
I also had to reinstall grunt and everything else I had installed globally via npm...
First, install stylus locally npm install stylus --save-dev if you haven't.
Create a startup script that builds your stylesheet and rebuilds whenever change detected in your main stylus file:
startup.js
var fs = require('fs')
var stylus = require('stylus')
// Define input filename and output filename
var styleInput = __dirname + '/dev/stylus/main.styl'
var styleOutputFilename = 'main.css'
var styleOutput = __dirname + '/static/' + styleOutputFilename
var stylusPaths = [__dirname + '/dev/stylus', __dirname + '/dev/stylus/libs']
// Build stylesheet on first execute
buildStyles(styleInput, styleOutput, stylusPaths)
// Watch stylus file for changes.
fs.watch(styleInput, function(eventType, filename) {
if (filename) {
buildStyles(styleInput, styleOutput, stylusPaths)
} else {
console.log('no filename found. probably platform doesnt support it.');
}
});
function buildStyles(input, output, paths) {
stylus(fs.readFileSync(input, 'utf-8'))
.set('paths', paths)
.set('include css', true)
.set('watch', true)
.render(function(err, css) {
if (err) throw err;
fs.writeFile(output, css, (err) => {
if (err) throw err;
console.log('👍 Stylesheet built successfully.');
});
});
}
Type node startup.js in the terminal. You will see a message "Stylesheet built successfully." whenever you change your main stylus file.
There is good documentation about stylus javascript api in their website.
OK I edited my answer because you do not want to make a homepage and then connect-assets makes no sense and can not help you... but maybe this,...
http://thechangelog.com/post/3036532096/stylus-expressive-robust-feature-rich-css-language
on that site you find at the bottom a video which shows close to the end how to use stylus via command line...
HTH and sorry for the misunderstanding...

Resources