Is there an easy way to reference all js files in an HTML file rather than referencing it one by one?
Instead of this -
<script type="text/javascript" src="js/controllers/mainCtrl.js"></script>
<script type="text/javascript" src="js/controllers/browseCtrl.js"></script>
...
I'm looking for something like this -
<script type="text/javascript" src="js/controllers/*.js"></script>
Or is there a tool out there that copies the contents of these files into one file and reference that one file instead? This will be minimize the HTTP calls.
Is there an easy way to reference all js files in an HTML file rather than referencing it one by one?
For some value of "easy". There is nothing built in to browsers that will do it though.
Or is there a tool out there that copies the contents of these files into one file and reference that one file instead?
There are many. cat is the simplest one.
Call it from your usual build tool.
You can use something like require.js to combine them at runtime during development, and call r.js via Node from your build tool for packaging for your staging and live environments.
You can give Require.js a go. Require.js is the only JavaScript-file that is loaded through the script-tag. When you go out of development you can use Require.js's r.js to minify and concat everything into one file.
I use this tool all the time to minify my JS files:
Online Javascript Compression Tool
You can upload multiple files and it will concatenate them into one for you. It also produces smaller filesizes than YUI compressor, and Google's JS compiler most of the time too.
I am not sure why this hasn't been mentioned yet, but I do suppose this thread is a bit dated. Since I stumbled on this during my search to solve this very problem, I thought I would put a quick write-up about GruntJS here for other newbie JS guys to find.
Essentially, a properly configured Gruntfile.js will be able to perform a variety of tasks around JS including, but not limited to: concatenating files, minifying files, code linting, and much much more.
You can install grunt on Ubuntu with:
$ sudo apt-get install nodejs
$ sudo npm -g install grunt-cli
$ cd /path/to/my/project
--- Assumming you have a package.json file already in place ---
$ npm install grunt --save-dev
--- Install grunt plugins you wish to use ---
$ npm install grunt-contrib-concat --save-dev
$ npm install grunt-contrib-uglify --save-dev
$ npm install grunt-contrib-jshint --save-dev
$ npm install grunt-contrib-watch --save-dev
On the GruntJS site, there is a pretty good write-up for how to use GruntJS, but here is an example Gruntfile.js that will:
Lint all the JS files (app.js in the current directory and all .js files in the ngmodules directory).
Concatenate and save the files to dist/package-name.js.
Minify the concatenated file and save it to dist/package-name.min.js.
Gruntfile.js:
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';'
},
dist: {
src: ['app.js', 'ngmodules/**/*.js'],
dest: 'dist/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
dist: {
files: {
'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
}
}
},
jshint: {
files: ['Gruntfile.js', 'app.js', 'ngmodules/**/*.js'],
options: {
// options here to override JSHint defaults
globals: {
jQuery: true,
console: true,
module: true,
document: true
}
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('default', ['jshint', 'concat', 'uglify']);
};
There is also Gulp (http://gulpjs.com/), which can be used with various plugins. Here's an example that concatenates *.js files in one single file (main.js), then renames the resulting file and finally minifies it:
var gulp = require('gulp'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat');
gulp.task('scripts', function(){
return gulp.src('./src/js/*.js')
.pipe(concat('main.js'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('./src/js/*.js'));
You can try and combine your javascript files or plugins into one:
<script type="text/javascript" src="js/controllers/plugins.js"></script>
You'll have to do it manually though.
Another option would be to write a server-side script to combine and minify all your javascript files.
Related
I currently have grunt-browserify to build a few js files into a bundle. I'm trying to add css into the bundle via require('./style.css'). I've been researching some options to do this and found the browserify-css library (https://www.npmjs.com/package/browserify-css). However there is no grunt support so I'm not sure how to add this to my existing grunt settings.
It seems that I need to add browserify-css as a transform option. The grunt-browserify says that the transform option takes an array of tasks (see below). However, I don't think browserify-css can be written as a grunt task. What's the best practice in this situation?
browserify: {
dist: {
files: {
'dist/bundle.js': 'js/index.js'
}
},
transform: ['coffeify']
}
I checked the source code of browserify, and I found this solution:
browserify: {
dist: {
src: 'js/index.js',
dest: 'dist/bundle.js'
},
options: {
transform: [['browserify-css', { global: true }]]
}
}
This works for me when I need to copy css files from node_modules folder. For make it work you only need to run:
npm install browserify browserify-css grunt-browserify --save-dev
and that's it!.
I have a Javascript project with multiple subdirectories, each its own individual project. I could just use one massive Gruntfile with different tasks for each project, but I'd rather have a Gruntfile in each subfolder. A typical file structure would be this
main_folder/
project_1
src
js/
dist/
doc/
Gruntfile.js
package.json
package.json
node_modules/
And then repeat the file structure for each project
Here is my Gruntfile inside project_1
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', ['uglify']);
};
It has fewer tasks than I will use, but the errors are still there. Whenever I try to run grunt, I get the error message Local Npm module "grunt-contrib-uglify" not found. Is it installed?, even though I have it installed in node_modules.
How can I specify the location of node_modules, or do I have to reinstall node_modules inside each folder?
I think you can still keep everything in the same place if you tell Grunt more explicitly where to find your plugins. For example, here's a bit from one of my Gruntfiles:
grunt.loadTasks tasks for tasks in grunt.file.expand '../node_modules/grunt-*/tasks'
As a side note: I faced exactly the same choice you did, but made the opposite choice: a single Gruntfile for the whole project and created a symlink to it from each project sub-directory. It's turned out to be a very easy way to keep things together in one place, and side-steps a lot of confusing issues like the one you're facing.
Another good way to solve this might be the use of subgrunt. It let's you configure various targets for your subprojects and has the option npmInstall, which "Determines wether npm install will be ran for the sub-project (thus installing dev dependencies)."
I'm configuring my Gruntfile and I'm stuck on something I feel should be possible but I'm not able to find the right configuration for it. I'm trying to copy my bower components to my dist on build with the grunt-contrib-requirejs module. The part I'm stuck on is keeping the folder structure in tact when copying to dist.
My app's basic structure, and dist/ should build the same way
Gruntfile.js
app/
- assets/
- bower_components/
- js/
- img/
- etc/
- index.html
Currently, I define each file in the copy module and it copy's them all over
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: 'app',
dest: 'dist',
src: [
'*.{ico,png}',
'.htaccess',
'partials/**/*',
// Bower Components
'assets/bower_components/requirejs/require.js',
'assets/bower_components/fastclick/lib/fastclick.js',
'assets/bower_components/jquery/dist/jquery.min.js',
'assets/bower_components/modernizr/modernizr.js'
]
}]
}
},
But I want to eliminate this and use the paths I've already defined in main.js to copy these files over. Less hardcoded stuff, more automation.
My require task
requirejs: {
dist: {
options: {
mainConfigFile: app + '/assets/js/main.js',
dir: dist + '/assets/js',
optimize: 'uglify',
paths: {
modernizr: 'empty:',
jquery: 'empty:',
fastclick: 'empty:'
}
}
}
},
This current configuration combined with copy moves them all over properly. If I could eliminate the paths property all together and use directory properties only that would be great. If I have to copy my paths from my main.js into here thats ok... if it's the only way to do it.
Let me know if you need any more info!
The JS files in your bower directory should be included in the optimized output of requirejs, as long as they are configured and referenced in your require js app. If they're not referenced as dependencies, I don't think they get included.
The ico, png, htaccess and other files may need to be copied over manually.
Depending on your partials, the text plugin and hbs plugin could compile those into the optimized file I think.
I think defining empty: in paths are for using network resources (e.g. when using CDNs instead of using local bower libraries), so the paths config is probably unnecessary
I have the following simple structure for my website:
src
js
core.js
main.js
lib
jquery-1.8.2.js
require-2.1.1.js
require-text.js
templates
1.html
2.html
index.html
build
I want all js+lib files to be compiled into one build/js/main.js file and other files just to be copied to build folder. How to write grunt.js config for this task? It seems I should use grunt-contrib-require..
The second question is how to compile 1.html and 2.html (I use require text! plugin) into one line for each and include theese lines to build/js/main.js? This case there should be only two files into build folder - index.html and main.js.
Take a look at grunt-contrib-requirejs and see if it is helpful to you.
The Grunt Website offers a very good tutorial to get you started, this is what you will need:
grunt-contrib-concat - To put files together in one
grunt-contrib-copy - To copy files to your "build" folder
grunt-usemin - To use the compiled js file in your html
I am not sure how to put those html files together though, feels weird to do that but maybe you can find a plugin for it.
Your Gruntfile.js should reside at the root of the directory i.e ls should show src/ build/ Gruntfile.js
Contents of `Gruntfile.js specific for your requirements:
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
js: {
src: [
'src/js/*', 'src/lib/*'
],
dest: 'build/js/combined.js'
}
},
uglify: {
js: {
files: {
'build/js/main.js': ['build/js/combined.js']
}
}
},
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', ['concat:js', 'uglify:js']);
};
I don't think require-js to be used here. Require-js is helpful when you need to load your js scripts in a specific order. If that being the case add the below code in your Gruntfile.js just below pkg: grunt.file.readJSON('package.json'), line
requirejs: {
compile: {
options: {
baseUrl: "path/to/base",
mainConfigFile: "path/to/config.js",
name: "path/to/almond", // assumes a production build using almond
out: "path/to/optimized.js"
}
}
}
You might consider adding grunt-require to the list that luschn put together. It uses r.js, has lots of options, and is pretty darn nice.
I have a node app that includes multiple unpublished modules. My app's package.json includes a few git dependencies:
"module-a": "git+ssh://git#github.com:me/module-a.git",
"module-b": "git+ssh://git#github.com:me/module-b.git"
and each of those have their own grunt config. Eg in node_modules/module-a/grunt.js:
module.exports = function(grunt) {
grunt.initConfig({
lint: {
files: ['server/**/*.js', 'test/**/*.js']
},
jshint: {
options: require('./lint-ci')
}
});
grunt.registerTask('default', 'lint');
};
(they also run tests, etc, but I'm keeping it simple here)
Is there a built-in way to do this with grunt? Note that I want to keep the dependent grunt.js files for convenience when I've only changed something within that dependency.
The only solutions I have found are
build up my main grunt.js programmatically (eg, iterating over my dependencies in package.json to build the lint and test config)
call grunt multiple times using --config node_modules/module-a/grunt.js
Neither seems ideal. Is there a better way?
Just a thought but have you looked at grunt-hub?
https://github.com/shama/grunt-hub