grunt-replace-withinit

0.6.2 • Public • Published

grunt-replace Build Status

Replace text patterns with a given replacement.

Getting Started

This plugin requires Grunt ~0.4.0

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-replace --save-dev

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

grunt.loadNpmTasks('grunt-replace');

This plugin was designed to work with Grunt 0.4.x. If you're still using grunt v0.3.x it's strongly recommended that you upgrade, but in case you can't please use v0.3.2.

Replace task

Run this task with the grunt replace command.

Task targets, files and options may be specified according to the grunt Configuring tasks guide.

Options

patterns

Type: Array

Define patterns that will be used to replace the contents of source files.

The matches will be sorted to prevent replacement issues like head / header (typo regexps will be resolved at last).

patterns.match

Type: String|RegExp

Indicates the matching expression.

If matching type is String and expression attribute is false we use a simple variable lookup mechanism @@string (in any other case we use the default regexp replace logic):

options: {
  patterns: [
    {
      match: 'foo',
      replacement: 'bar', // replaces "@@foo" to "bar"
      expression: false   // simple variable lookup
    }
  ]
}

Templated regexps are allowed, match attribure must be quoted and expression attribute should be in true:

options: {
  patterns: [
    {
      match: '/<%= grunt.template.date(847602000000, "yyyy") %>/g',
      replacement: '2014', // replaces "1996" to "2014"
      expression: true     // must be forced for templated regexp
    }
  ]
}

patterns.replacement

Type: String|Function|Object

Indicates the replacement for match, for more information about replacement checkout String.replace.

You can specify a function as replacement. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string.

options: {
  patterns: [
    {
      match: /foo/g,
      replacement: function () {
        return 'bar'; // replaces "foo" to "bar"
      }
    }
  ]
}

Also supports object as replacement (we create string representation of object using JSON.stringify):

options: {
  patterns: [
    {
      match: /foo/g,
      replacement: [1, 2, 3] // replaces "foo" with string representation of "array" object
    }
  ]
}

patterns.json

Type: Object

If an attribute json found in pattern definition we flatten the object using dotted concatenation and each key–value pair will be used for the replacement (simple variable lookup mechanism and no regexp support).

options: {
  patterns: [
    {
      json: {
        "key": "value" // replaces "@@key" to "value"
      }
    }
  ]
}

Also supports nested objects and templating:

options: {
  patterns: [
    {
      json: {
        "key": "value",   // replaces "@@key" to "value"
        "inner": {        // replaces "@@inner" with string representation of "inner" object
          "key": "value"  // replaces "@@inner.key" to "value"
        }
      }
    }
  ]
}

Alternatively, you can specify a external file:

options: {
  patterns: [
    {
      json: grunt.file.readJSON('config.json')
    }
  ]
}

patterns.expression

Type: Boolean Default: false

Indicates the type of matching (for templated regexp match we need to force in true).

If detects regexp instance in match attribute we assume to works with expression matcher (in any other case should be forced).

variables

Type: Object

This is the old way to define patterns using plain object (simple variable lookup mechanism and no regexp support), you can still using but for more control you should use the new patterns way.

options: {
  variables: {
    'key': 'value' // replaces "@@key" to "value"
  }
}

prefix

Type: String Default: @@

The prefix added to patterns.match for easy matching and replace error prevention.

This only applies for simple variable lookup mechanism.

usePrefix

Type: Boolean Default: true

If set to false, we match the string in patterns.match without prefix concatenation. It was useful when you want to look up an simple string.

This only applies for simple variable lookup mechanism.

preservePrefix

Type: Boolean Default: false

If set to true, we preserve the prefix in target.

This only applies for simple variable lookup mechanism and patterns.replacement is an string.

force

Type: Boolean Default: false

Force the copy of files even when those files don't have any match found for replacement.

noProcess

Type: String

This option is an advanced way to control which file contents are processed.

processContentExclude has been renamed to noProcess and the option name will be removed in the future.

encoding

Type: String Default: grunt.file.defaultEncoding

The file encoding to copy files with.

mode

Type: Boolean or Number Default: false

Whether to copy or set the existing file permissions. Set to true to copy the existing file permissions. Or set to the mode, i.e.: 0644, that copied files will be set to.

Usage Examples

Short

File build/manifest.appcache:

CACHE MANIFEST
# @@timestamp

CACHE:

favicon.ico
index.html

NETWORK:
*

Gruntfile, define pattern (for timestamp) and the source files for lookup:

replace: {
  dist: {
    options: {
      patterns: [
        {
          match: 'timestamp',
          replacement: '<%= grunt.template.today() %>'
        }
      ]
    },
    files: [
      {expand: true, flatten: true, src: ['build/manifest.appcache'], dest: 'public/'}
    ]
  }
}

Multiple matching

File build/manifest.appcache:

CACHE MANIFEST
# @@timestamp

CACHE:

favicon.ico
index.html

NETWORK:
*

File build/humans.txt:

              __     _
   _    _/__  /./|,//_`
  /_//_// /_|///  //_, outaTiME v.@@version

/* TEAM */
  Web Developer / Graphic Designer: Ariel Oscar Falduto
  Site: http://www.outa.im
  Twitter: @outa7iME
  Contact: afalduto at gmail dot com
  From: Buenos Aires, Argentina

/* SITE */
  Last update: @@timestamp
  Standards: HTML5, CSS3, robotstxt.org, humanstxt.org
  Components: H5BP, Modernizr, jQuery, Twitter Bootstrap, LESS, Jade, Grunt
  Software: Sublime Text 2, Photoshop, LiveReload

Gruntfile:

replace: {
  dist: {
    options: {
      patterns: [
        {
          match: 'version',
          replacement: '<%= pkg.version %>'
        },
        {
          match: 'timestamp',
          replacement: '<%= grunt.template.today() %>'
        }
      ]
    },
    files: [
      {expand: true, flatten: true, src: ['build/manifest.appcache', 'build/humans.txt'], dest: 'public/'}
    ]
  }
}

Cache busting

File app/assets/index.html:

<head>
  <link rel="stylesheet" href="/css/style.css?rel=@@timestamp">
  <script src="/js/app.js?rel=@@timestamp"></script> 
</head>

Gruntfile:

replace: {
  dist: {
    options: {
      patterns: [
        {
          match: 'timestamp',
          replacement: '<%= new Date().getTime() %>'
        }
      ]
    },
    files: [
      {src: ['app/assets/index.html'], dest: 'build/index.html'}
    ]
  }
}

Include file

File build/index.html:

<body>
  @@include
</body>

Gruntfile:

replace: {
  dist: {
    options: {
      patterns: [
        {
          match: 'include',
          replacement: '<%= grunt.file.read("includes/content.html") %>'
        }
      ]
    },
    files: [
      {expand: true, flatten: true, src: ['build/index.html'], dest: 'public/'}
    ]
  }
}

Regular expression

File build/username.txt:

John Smith

Gruntfile:

replace: {
  dist: {
    options: {
      patterns: [
        {
          match: /(\w+)\s(\w+)/,
          replacement: '$2, $1', // replaces "John Smith" to "Smith, John"
          expression: true
        }
      ]
    },
    files: [
      {expand: true, flatten: true, src: ['build/username.txt'], dest: 'public/'}
    ]
  }
}

Lookup for foo instead of @@foo

The String matching type or expression in false generates a simple variable lookup mechanism @@string, to skip this mode use one of the below rules ... make your choice:

Gruntfile:

 
// option 1 (explicitly using an regexp)
 
replace: {
  dist: {
    options: {
      patterns: [
        {
          match: /foo/g,
          replacement: 'bar'
        }
      ]
    },
    files: [
      {expand: true, flatten: true, src: ['build/foo.txt'], dest: 'public/'}
    ]
  }
}
 
// option 2 (easy way)
 
replace: {
  dist: {
    options: {
      patterns: [
        {
          match: 'foo',
          replacement: 'bar'
        }
      ],
      usePrefix: false
    },
    files: [
      {expand: true, flatten: true, src: ['build/foo.txt'], dest: 'public/'}
    ]
  }
}
 
// option 3 (old way)
 
replace: {
  dist: {
    options: {
      patterns: [
        {
          match: 'foo',
          replacement: 'bar'
        }
      ],
      prefix: '' // remove prefix
    },
    files: [
      {expand: true, flatten: true, src: ['build/foo.txt'], dest: 'public/'}
    ]
  }
}
 

Release History

  • 2014-02-06   v0.6.1   Rename excludePrefix to preservePrefix (more readable) and adds usePrefix flag. Support the noProcess option like grunt-contrib-copy.
  • 2014-02-05   v0.6.0   Object replacement allowed. New excludePrefix flag (thanks @shinnn). Encoding / Mode options added.
  • 2013-09-18   v0.5.1   New pattern matching for JSON object.
  • 2013-09-17   v0.5.0   Regular expression matching now supported and notation has been updated but is backward compatible.
  • 2013-05-03   v0.4.4   Fix escape $ before performing regexp replace (thanks @warpech).
  • 2013-04-14   v0.4.3   Detect path destinations correctly on Windows.
  • 2013-04-02   v0.4.2   Add peerDependencies and update description.
  • 2013-04-02   v0.4.1   Add trace when force flag.
  • 2013-02-28   v0.4.0   First official release for Grunt 0.4.0.
  • 2012-11-20   v0.3.2   New examples added.
  • 2012-09-25   v0.3.1   Rename grunt-contrib-lib dep to grunt-lib-contrib, add force flag.
  • 2012-09-25   v0.3.0   General cleanup and consolidation. Global options depreciated.

Task submitted by Ariel Falduto

Readme

Keywords

none

Package Sidebar

Install

npm i grunt-replace-withinit

Weekly Downloads

1

Version

0.6.2

License

none

Last publish

Collaborators

  • abc-team