├── .gitignore ├── .travis.yml ├── test ├── fixtures │ ├── foo.js │ └── app.js ├── index.js └── build.js ├── .editorconfig ├── package.json ├── license ├── lib └── index.js └── readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | *.log 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 6 4 | -------------------------------------------------------------------------------- /test/fixtures/foo.js: -------------------------------------------------------------------------------- 1 | var FOO = DEMO_FOO; 2 | 3 | module.exports = () => `foo: ${ FOO }`; 4 | -------------------------------------------------------------------------------- /test/fixtures/app.js: -------------------------------------------------------------------------------- 1 | import mri from 'mri'; 2 | import foo from './foo'; 3 | 4 | mri([]); 5 | 6 | console.log(` 7 | ENV: process.env.NODE_ENV 8 | BAR: DEMO_BAR 9 | FOO: FOO_BAR 10 | BAZ: FOO_BAZ 11 | ${ foo() } 12 | `); 13 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_size = 2 5 | indent_style = tab 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | 11 | [*.{json,yml,md}] 12 | indent_style = space 13 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | const { readFileSync } = require('fs'); 2 | const { join } = require('path'); 3 | const test = require('tape'); 4 | const fn = require('../lib'); 5 | 6 | const file = join(__dirname, '.tmp', 'out.js'); 7 | 8 | test('ReplaceText', t => { 9 | t.equal(typeof fn, 'function', 'exports a function'); 10 | t.end(); 11 | }); 12 | 13 | test('Usage', t => { 14 | const str = readFileSync(file, 'utf8'); 15 | t.true(/DEMO_FOO/g.test(str), 'respects `foo.js` exclusion (via config)'); 16 | t.true(/const FLAG/g.test(str), 'respects `node_module` exclusion (via config)'); 17 | t.false(/FOO_/g.test(str), 'replaces all `FOO_*` patterns via RegExp (via config)'); 18 | t.false(/process.env.NODE_ENV/g.test(str), 'replaces all `process.env.NODE_ENV` occurrences (via config)'); 19 | t.end(); 20 | }); 21 | -------------------------------------------------------------------------------- /test/build.js: -------------------------------------------------------------------------------- 1 | const { join } = require('path'); 2 | const webpack = require('webpack'); 3 | const rimraf = require('rimraf'); 4 | const Lib = require('../lib'); 5 | 6 | const tmp = join(__dirname, '.tmp'); 7 | const src = join(__dirname, 'fixtures'); 8 | 9 | rimraf(tmp, () => { 10 | webpack({ 11 | entry: `${src}/app.js`, 12 | output: { path:tmp, filename:'out.js' }, 13 | plugins: [ 14 | new Lib({ 15 | exclude: [/node_modules/, 'foo.js'], 16 | values: { 17 | 'DEMO_FOO': 123, 18 | 'DEMO_BAR': '"world"', 19 | 'const FLAG': '"FLAGGG"', 20 | 'process.env.NODE_ENV': JSON.stringify('production'), 21 | }, 22 | patterns: [ 23 | { regex: /FOO_[^\*]{3}(\s)?/g, value:123 }, 24 | ] 25 | }) 26 | ] 27 | }, (err, stats) => { 28 | if (err || stats.hasErrors()) { 29 | return console.log('Build error!'); 30 | } 31 | }); 32 | }); 33 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "webpack-plugin-replace", 3 | "description": "Replace content while bundling.", 4 | "version": "1.2.0", 5 | "main": "lib/index.js", 6 | "license": "MIT", 7 | "author": { 8 | "name": "Luke Edwards", 9 | "email": "luke.edwards05@gmail.com", 10 | "url": "lukeed.com" 11 | }, 12 | "scripts": { 13 | "pretest": "node test/build", 14 | "test": "tape test/index.js | tap-spec" 15 | }, 16 | "keywords": [ 17 | "bundle", 18 | "content", 19 | "plugin", 20 | "replace", 21 | "string", 22 | "text", 23 | "webpack", 24 | "webpack-plugin" 25 | ], 26 | "files": [ 27 | "lib" 28 | ], 29 | "engines": { 30 | "node": ">=4" 31 | }, 32 | "devDependencies": { 33 | "mri": "^0.1.0", 34 | "rimraf": "^2.6.1", 35 | "tap-spec": "^4.1.1", 36 | "tape": "^4.6.3", 37 | "webpack": "^2.6.1" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Luke Edwards (lukeed.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | const isRegex = any => any instanceof RegExp; 2 | const isBool = any => typeof any === 'boolean'; 3 | const isString = any => typeof any === 'string'; 4 | const isFunction = any => typeof any === 'function'; 5 | 6 | const toArray = any => Array.isArray(any) ? any : (any == null ? [] : [any]); 7 | 8 | function toRegexMap(arr) { 9 | let i=0, len=arr.length, map=new Map(); 10 | for (; i < len; i++) { 11 | if (!('regex' in arr[i] && 'value' in arr[i])) continue; 12 | map.set(arr[i].regex, arr[i].value); 13 | } 14 | return map; 15 | } 16 | 17 | function toFunction(val) { 18 | if (isBool(val)) return _ => val; 19 | if (isRegex(val)) return str => val.test(str); 20 | if (isString(val)) return str => str.includes(val); 21 | if (isFunction(val)) return str => val(str); 22 | } 23 | 24 | function evalArr(funcs, str) { 25 | let i=0, len=funcs.length; 26 | for (; i < len; i++) { 27 | if (funcs[i](str) === true) { 28 | return true; // match ANY cond 29 | } 30 | } 31 | return false; 32 | } 33 | 34 | const NAME = 'webpack-plugin-replace'; 35 | 36 | class ReplaceText { 37 | constructor(opts) { 38 | opts = Object.assign({ include:true, exclude:false, patterns:[] }, opts); 39 | 40 | const includes = toArray(opts.include).map(toFunction); 41 | const excludes = toArray(opts.exclude).map(toFunction); 42 | 43 | this.options = opts; 44 | this.values = opts.values || opts; 45 | this.patterns = toRegexMap(opts.patterns); 46 | 47 | this.isMatch = str => (str !== void 0) && evalArr(includes, str) && !evalArr(excludes, str); 48 | } 49 | 50 | apply(compiler) { 51 | const vals = this.values; 52 | const pats = this.patterns; 53 | const keys = Object.keys(vals).filter(k => !/[ex,in]clude|patterns/.test(k)); 54 | const RGXP = new RegExp(keys.join('|'), 'g'); 55 | const isMatch = this.isMatch; 56 | 57 | function onOptimize(modules) { 58 | modules.forEach(mod => { 59 | if (isMatch(mod.resource)) { 60 | mod._source._value = mod._source._value.replace(RGXP, k => vals[k]); 61 | pats.forEach((v,k) => { 62 | mod._source._value = mod._source._value.replace(k, v); 63 | }); 64 | } 65 | }); 66 | } 67 | 68 | if (compiler.hooks !== void 0) { 69 | compiler.hooks.compilation.tap(NAME, bundle => { 70 | bundle.hooks.optimizeModules.tap(NAME, onOptimize); 71 | }); 72 | } else { 73 | compiler.plugin('compilation', bundle => { 74 | bundle.plugin('optimize-modules', onOptimize); 75 | }); 76 | } 77 | } 78 | } 79 | 80 | module.exports = ReplaceText; 81 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # webpack-plugin-replace [![Build Status](https://travis-ci.org/lukeed/webpack-plugin-replace.svg?branch=master)](https://travis-ci.org/lukeed/webpack-plugin-replace) 2 | 3 | > Replace content while bundling. 4 | 5 | 6 | ## Install 7 | 8 | ``` 9 | $ npm install --save-dev webpack-plugin-replace 10 | ``` 11 | 12 | 13 | ## Usage 14 | 15 | ```js 16 | // webpack.config.js 17 | const ReplacePlugin = require('webpack-plugin-replace'); 18 | 19 | module.exports = { 20 | // ... 21 | plugins: [ 22 | new ReplacePlugin({ 23 | exclude: [ 24 | 'foo.js', 25 | /node_modules/, 26 | filepath => filepath.includes('ignore') 27 | ], 28 | patterns: [{ 29 | regex: /throw\s+(new\s+)?(Type|Reference)?Error\s*\(/g, 30 | value: 'return;(' 31 | }], 32 | values: { 33 | 'process.env.NODE_ENV': JSON.stringify('production'), 34 | 'FOO_BAR': '"hello world"', 35 | 'DEV_MODE': false, 36 | } 37 | }) 38 | ] 39 | }; 40 | ``` 41 | 42 | 43 | ## API 44 | 45 | ### webpack-plugin-replace(options) 46 | 47 | #### options.exclude 48 | 49 | Type: `Array|String|Function|RegExp`
50 | Default: `false` 51 | 52 | If multiple conditions are provided, matching _any_ condition will exclude the filepath, which prevents any alterations. 53 | 54 | > **Note:** By default, nothing is excluded! 55 | 56 | #### options.include 57 | 58 | Type: `Array|String|Function|RegExp`
59 | Default: `true` 60 | 61 | If multiple conditions are provided, matching _any_ condition will include & scan the filepath for eligible replacements. 62 | 63 | > **Note:** By default, all filepaths are included! 64 | 65 | #### options.patterns 66 | 67 | Type: `Array`
68 | Default: `[]` 69 | 70 | An array of `RegExp` pattern definitions. Each definition is an object with `regex ` and `value ` keys. If `value` is a function, it takes the same arguments as [`String.prototype.relace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter). 71 | 72 | #### options.values 73 | 74 | Type: `Object`
75 | Default: `{}` 76 | 77 | An object whose keys are `strings` that should be replaced and whose values are `strings` the replacements. 78 | 79 | If desired, you may forgo the `values` key & declare your `key:value` pairs directly to the main configuration. For example: 80 | 81 | ```js 82 | { 83 | exclude: /node_modules/, 84 | values: { 85 | 'process.env.NODE_ENV': JSON.stringify('production'), 86 | } 87 | } 88 | 89 | // is the same as: 90 | 91 | { 92 | exclude: /node_modules/, 93 | 'process.env.NODE_ENV': JSON.stringify('production'), 94 | } 95 | ``` 96 | 97 | 98 | ## License 99 | 100 | MIT © [Luke Edwards](https://lukeed.com) 101 | --------------------------------------------------------------------------------