Skip to content

Instantly share code, notes, and snippets.

@ryanfitzer
Last active December 18, 2015 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanfitzer/5811201 to your computer and use it in GitHub Desktop.
Save ryanfitzer/5811201 to your computer and use it in GitHub Desktop.
Simple example project for using the grunt-preprocess task to easily build files based on custom variables. Use the "Download Gist" button to use as a readymade quickstart.

What is the grunt-preprocess task?

A task that preprocess HTML, JavaScript, and other files with directives based on of custom variables and/or your NODE_ENV configuration.

How do I Run this Example?

Install the dependencies:

$ cd into/project/root
$ npm install

Run the build:

$ grunt

What Should I Expect from the Build?

Grunt will create a new sibling directory named "preprocess-build". View "index.html" and (the newly created) "index_ca.html" in a browser to see the result of the preprocess task defined in "Gruntfile.js".

<h1>This Page is was Developed for Canada.</h1>
<h1>This Page is was Developed for the US.</h1>
module.exports = function( grunt ) {
grunt.initConfig({
pkg: grunt.file.readJSON( 'package.json' ),
buildPath: '../<%= pkg.name %>-build/',
clean: {
options: {
force: true
},
src: [ '<%= buildPath %>' ]
},
copy: {
dist: {
files: [
{
src: [
'**',
'!**/node_modules/**' // Pattern to exclude a directory.
],
dest: '<%= buildPath %>'
},
]
}
},
preprocess: {
options: {
context: {
RYAN: true
}
},
ca: {
options: {
context: {
RYAN: false,
REGION: 'CA',
BUILDSCRIPT: '<script src="build.js"></script>'
}
},
src: '<%= buildPath %>index.html',
dest: '<%= buildPath %>index_ca.html'
},
us: {
options: {
context: {
REGION: 'US',
BUILDSCRIPT: '<script src="build.js"></script>'
}
},
src: '<%= buildPath %>index.html',
dest: '<%= buildPath %>index.html'
}
}
});
grunt.loadNpmTasks( 'grunt-contrib-clean' );
grunt.loadNpmTasks( 'grunt-contrib-copy' );
grunt.loadNpmTasks( 'grunt-preprocess' );
grunt.registerTask( 'default', [
'clean',
'copy',
'preprocess'
]);
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Preprocess</title>
</head>
<body>
<!-- @exclude -->
<h1>This Page is Still in Development.</h1>
<!-- @endexclude -->
<!-- @if REGION='CA' -->
<!-- @include code-ca.txt -->
<!-- @endif -->
<!-- @if REGION='US' -->
<!-- @include code-us.txt -->
<!-- @endif -->
<!-- @echo BUILDSCRIPT -->
<!-- @exclude -->
<script src="vendor.js"></script>
<script src="plugin.js"></script>
<script src="main.js"></script>
<!-- @endexclude -->
</body>
</html>
{
"name": "preprocess",
"version": "0.0.1",
"dependencies": {
"grunt": "~0.4.1",
"grunt-preprocess": "~2.3.0",
"grunt-contrib-clean": "~0.4.1",
"grunt-contrib-copy": "~0.4.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment