• This repository has been archived on 15/Nov/2022
  • Stars
    star
    194
  • Rank 200,219 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 12 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Replace strings on files by using string or regex patterns.

grunt-string-replace Build Status

Replaces strings on files by using string or regex patterns. Attempts to be a String.prototype.replace adapter task for your grunt project.

Getting Started

This plugin requires node >= 0.10.0, Grunt >= 0.4.0 and npm >= 1.4.15 (latest stable is recommended).

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-string-replace --save-dev

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

grunt.loadNpmTasks("grunt-string-replace");

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.1.1-1.

Configuration

Inside your Gruntfile.js file add a section named string-replace. This section specifies the files to edit, destinations, patterns and replacements.

Parameters

files object

Defines what files this task will edit. Grunt itself has very powerful abstractions, so it is highly recommended you understand the different ways to specify them. Learn more at Gruntfile Files mapping, some options incude compact format, files object format and files array format.

options object

Controls how this task operates and should contain key:value pairs, see options below.

options.saveUnchanged boolean

By default true this flag will instruct grunt-string-replace to copy the files on options.replacements patterns even if there are no replacing matches.

By setting this flag to false files that have not changed (no replacements done) will not be saved on the new location. This will speed up the task if there is a large number of files.

options.replacements array

This option will hold all your pattern/replacement pairs. A pattern/replacement pair should contain key:value pairs containing:

  • pattern string or regex
  • replacement string
options: {
  replacements: [
    {
      pattern: /\/(asdf|qwer)\//gi,
      replacement: '"$1"',
    },
    {
      pattern: ",",
      replacement: ";",
    },
  ];
}

Notes

  • If the pattern is a string, only the first occurrence will be replaced, as stated on String.prototype.replace.
  • When using Grunt templates, be aware that some security checks are implemented by LoDash and may alter your content (mainly to avoid XSS). To avoid this, see the advanced example below.

Examples

Multiple files and multiple replacements

'string-replace': {
  dist: {
    files: {
      'dest/': 'src/**',
      'prod/': ['src/*.js', 'src/*.css'],
    },
    options: {
      replacements: [{
        pattern: /\/(asdf|qwer)\//ig,
        replacement: ''$1''
      }, {
        pattern: ',',
        replacement: ';'
      }]
    }
  }
}

Simple inline content

'string-replace': {
  inline: {
    files: {
      'dest/': 'src/**',
    },
    options: {
      replacements: [
        // place files inline example
        {
          pattern: '<script src='js/async.min.js'></script>',
          replacement: '<script><%= grunt.file.read('path/to/source/js/async.min.js') %></script>'
        }
      ]
    }
  }
}

Using files' expand options

For more details, see Grunt's documentation about dynamic files object.

'string-replace': {
  dist: {
    files: [{
      expand: true,
      cwd: 'src/',
      src: '**/*',
      dest: 'dist/'
    }],
    options: {
      replacements: [{
        pattern: 'hello',
        replacement: 'howdy'
      }]
    }
  }
}

Advanced inline

Since grunt-string-replace is basically a wrapper of String.prototype.replace you can also provide a function as a replacement pattern instead of a string or a template; as a nice added bonus to using a replacement function, grunt-string-replace will provide 2 extra arguments apart from the ones documented in the link below: src and dest. To get more details about how to use a function as replacement pattern I recommend you to read Specifying a function as a parameter.

We will be reading file names from HTML comments and use the paths later to fetch the content and insert it inside a resulting HTML. Assuming the following setup:

src/index.html

<!-- @import partials/header.html -->
content here
<!-- @import partials/footer.html -->

src/partials/header.html

<html>
  <head></head>
  <body></body>
</html>

src/partials/footer.html

</body></html>

Gruntfile.js

'use strict';

module.exports = function (grunt) {
  // Project configuration.
  grunt.initConfig({
    config: {
      src: 'src/*.html'
      dist: 'dist/'
    },
    'string-replace': {
      dist: {
        files: {
          '<%= config.dist %>': '<%= config.src %>'
        },
        options: {
          replacements: [{
            pattern: /<!-- @import (.*?) -->/ig,
            replacement: function (match, p1) {
              return grunt.file.read(grunt.config.get('config.dist') + p1);
            }
          }]
        }
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-string-replace');

  // Default task.
  grunt.registerTask('default', ['string-replace']);
};

After executing grunt we get the following:

dist/index.html

<html>
  <head></head>
  <body>
    content here
  </body>
</html>

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using grunt.

Release History

1.3.3

  • Sync docs, travis settings and code with npm (made a mess between GitHub and npm on 1.3.2).

1.3.2

  • Updated several dependencies. Some updates require node >= 8. If you need node < 8 stay on 1.3.1. Thanks to anand-gopinath for flagging some of them.

1.3.1

  • Misc updates.

1.3.0

  • Fix #39, a typo in the documentation
  • Inject src and dest into the callback function when replacement is a function; this allows the replacement function to use the old and/or new file paths/names for further processing
  • Add total files modified and update file created logging to verbose. Contributed by tHBp

1.2.1

  • Update project URLs
  • Update dependencies

1.2.0

  • Add saveUnchanged option to control weather unmodified files are saved or not.
  • Add iojs to Travis CI.

1.1.1

  • Add Node.js v0.12 to Travis CI

1.1.0

  • Update dependencies
  • Add new log and debug messages
  • Improved file handling; grunt-string-replace will not copy files that are not modified (no replacements executed). Contributed by iabw

1.0.0

  • Update dependencies
  • Update README.md
  • Well deserved bump to 1.0.0 (its been stable for long enough now)

0.2.8

  • Added log message after file is succesfully created. Contributed by donaldpipowitch
  • Do not report error if one of the replacements resolves to a folder

0.2.7

  • External libraries are deprecated on Grunt 0.4.2

    • Remove grunt.util._ as it is not really required
    • Replace grunt.util.async with async

0.2.6

  • Update Getting Started section
  • Fix broken link to Gruntfile's File section (#18)

0.2.5

  • Fix for #16
  • Fix for Travis CI config file
  • Added error handling to finish the task if something did not work as expected instead of just fail silently
  • Updated dev dependencies to latest stable versions

0.2.4

  • Asynchronously loop files. Original idea contributed by maxnachlinger
  • Inline replacing example on README.md. Contributed by willfarrell

0.2.3

  • Removed dependency with grunt-lib-contrib due to deprecation of 'options' method in favor of Grunt's 'options' util.
  • Updated grunt-contrib-jshint version in package.json to 0.3.0
  • Updated grunt-contrib-watch version in package.json to 0.3.1
  • Updated grunt version in package.json to 0.4.1
  • Added Node.js v0.10 to Travis CI config file

0.2.2

  • Added support to be used as npm module. Contributed by thanpolas.

0.2.1

  • Updated dependencies for Grunt 0.4.0.

0.2.0

  • Added Support for grunt 0.4.0. This version will not support grunt 0.3.x, if you need to use it then npm install [email protected].

0.1.1-1

  • Added Clean task (and dev dependency) to remove test generated file before testing.
  • Added Sublime Text project files and test generated file to npm ignore list.

0.1.1

  • Fix dependency with grunt-lib-contrib.

0.1.0-1

  • Fixed a typo on package.json description.
  • Added a note about string pattern behavior.

0.1.0

  • Initial release.

License

Copyright (c) 2016 Erick Ruiz de Chavez. Licensed under the MIT license.

More Repositories

1

demo-chat

Playing with Node.js and Socket.io
JavaScript
26
star
2

rlbb

"Real Life" Backbone Demo
JavaScript
20
star
3

twitter-demo

A demo of nodejs, oauth, handlebars and socketio
JavaScript
10
star
4

contact

A basic clone of formspree.io for internal use
JavaScript
9
star
5

mdwiki

Markdown Wiki Server for Local usage
JavaScript
8
star
6

node-mysql-demo

An enxample on how to use MySQL connection on Node.js
JavaScript
7
star
7

json-response

API-ish JSON response for express using basic fields (status, data, message). DRY.
JavaScript
6
star
8

taller-backbone

JavaScript
4
star
9

npcp

npm package config parser
JavaScript
3
star
10

local-bin

A local fake server that captures http requests and leverages ngrok to show a nice inspector
JavaScript
3
star
11

lets-git-together

HTML
2
star
12

contador

Un pequeño script que crea una cuenta regresiva
JavaScript
2
star
13

workers

A simple example of webworkers
JavaScript
2
star
14

webapp-requirejs

Web app ready for start coding. Includes jQuery, Bootstrap, Backbone.js, Underscore.js and RequireJS.
JavaScript
2
star
15

sync

Backbone.Sync examples for 3 different back end styles
JavaScript
2
star
16

qrcode-vcard

QR Code VCard Generator for Node.js
JavaScript
2
star
17

tdw1-src

Repositorio de trabajo para el Taller de desarrollo web
Ruby
2
star
18

php-node-redis

A quick example of Node.js reading PHP session on Redis
PHP
1
star
19

php-node-dynamodb

A quick example of Node.js reading PHP session on DynamoDB
JavaScript
1
star
20

handlebars-demo

JavaScript
1
star
21

backbone-require

A Backbone.js and RequireJS example
JavaScript
1
star
22

micro-frontend-experiments

A collection of Micro Frontend and Web Component experiments.
TypeScript
1
star
23

tdw1

Taller de desarrollo web (v1)
1
star
24

talks

JavaScript
1
star
25

backbone-views-demo

Un ejemplo del manejo de Vistas, Modelos y Colecciones en Backbone
JavaScript
1
star