[Pkg-javascript-commits] [node-rollup-plugin-replace] 01/08: New upstream version 2.0.0

Julien Puydt julien.puydt at laposte.net
Fri Sep 8 06:08:49 UTC 2017


This is an automated email from the git hooks/post-receive script.

jpuydt-guest pushed a commit to branch master
in repository node-rollup-plugin-replace.

commit 84d9bb49ed4f233b7a2d50c9f73ba4a4db442d0d
Author: Julien Puydt <julien.puydt at laposte.net>
Date:   Wed Sep 6 07:38:41 2017 +0200

    New upstream version 2.0.0
---
 .travis.yml                        |   3 +-
 CHANGELOG.md                       |  13 +++++
 README.md                          |  57 ++++++++++++++++++---
 appveyor.yml                       |   3 +-
 package.json                       |  23 ++++-----
 rollup.config.js                   |  11 ++--
 src/index.js                       |  65 ++++++++++++++++++------
 test/index.js                      |  25 ----------
 test/samples/basic/main.js         |   6 +--
 test/samples/boundaries/main.js    |   2 +
 test/samples/longest-first/main.js |   1 +
 test/samples/relative/dir/foo.js   |   1 +
 test/samples/relative/main.js      |   5 ++
 test/samples/special-chars/main.js |   2 +
 test/test.js                       | 100 +++++++++++++++++++++++++++++++++++++
 15 files changed, 244 insertions(+), 73 deletions(-)

diff --git a/.travis.yml b/.travis.yml
index 9a040ed..07313ea 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,8 +1,7 @@
 sudo: false
 language: node_js
 node_js:
-  - "0.12"
-  - "4"
+  - "stable"
 env:
   global:
     - BUILD_TIMEOUT=10000
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e4d814..1b47960 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,18 @@
 # rollup-plugin-replace changelog
 
+## 2.0.0
+
+* Only match on word boundaries, unless delimiters are empty strings ([#10](https://github.com/rollup/rollup-plugin-replace/pull/10))
+
+## 1.2.1
+
+* Match longest keys first ([#8](https://github.com/rollup/rollup-plugin-replace/pull/8))
+* Escape keys ([#9](https://github.com/rollup/rollup-plugin-replace/pull/9))
+
+## 1.2.0
+
+* Allow replacement to be a function that takes a module ID ([#1](https://github.com/rollup/rollup-plugin-replace/issues/1))
+
 ## 1.1.1
 
 * Return a `name`
diff --git a/README.md b/README.md
index fb4ae62..1653e7d 100644
--- a/README.md
+++ b/README.md
@@ -12,18 +12,21 @@ npm install --save-dev rollup-plugin-replace
 
 ## Usage
 
+Generally, you need to ensure that rollup-plugin-replace goes *before* other things (like rollup-plugin-commonjs) in your `plugins` array, so that those plugins can apply any optimisations such as dead code removal.
+
+
 ```js
-import { rollup } from 'rollup';
+// rollup.config.js
 import replace from 'rollup-plugin-replace';
 
-rollup({
-  entry: 'main.js',
+export default {
+  // ...
   plugins: [
     replace({
-      ENVIRONMENT: JSON.stringify( 'production' )
+      ENVIRONMENT: JSON.stringify('production')
     })
   ]
-}).then(...)
+};
 ```
 
 
@@ -42,23 +45,61 @@ rollup({
 
   // To replace every occurence of `<@foo@>` instead of every
   // occurence of `foo`, supply delimiters
-  delimiters: [ '<@', '@>' ],
+  delimiters: ['<@', '@>'],
 
   // All other options are treated as `string: replacement`
   // replacers...
   VERSION: '1.0.0',
-  ENVIRONMENT: JSON.stringify( 'development' ),
+  ENVIRONMENT: JSON.stringify('development'),
+
+  // or `string: (id) => replacement` functions...
+  __dirname: (id) => `'${path.dirname(id)}'`,
 
   // ...unless you want to be careful about separating
   // values from other options, in which case you can:
   values: {
     VERSION: '1.0.0',
-    ENVIRONMENT: JSON.stringify( 'development' )
+    ENVIRONMENT: JSON.stringify('development')
   }
 }
 ```
 
 
+## Word boundaries
+
+By default, values will only match if they are surrounded by *word boundaries* — i.e. with options like this...
+
+```js
+{
+  changed: 'replaced'
+}
+```
+
+...and code like this...
+
+```js
+console.log('changed');
+console.log('unchanged');
+```
+
+...the result will be this:
+
+```js
+console.log('replaced');
+console.log('unchanged');
+```
+
+If that's not what you want, specify empty strings as delimiters:
+
+```js
+{
+  changed: 'replaced',
+  delimiters: ['', '']
+}
+```
+
+
+
 ## License
 
 MIT
diff --git a/appveyor.yml b/appveyor.yml
index 6877afb..5ff3e17 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -10,8 +10,7 @@ init:
 environment:
   matrix:
     # node.js
-    - nodejs_version: 0.12
-    - nodejs_version: 4
+    - nodejs_version: stable
 
 install:
   - ps: Install-Product node $env:nodejs_version
diff --git a/package.json b/package.json
index 3775f21..3bae77c 100644
--- a/package.json
+++ b/package.json
@@ -1,23 +1,23 @@
 {
   "name": "rollup-plugin-replace",
-  "version": "1.1.1",
+  "version": "2.0.0",
   "devDependencies": {
-    "eslint": "^2.13.1",
-    "mocha": "^2.5.3",
-    "rollup": "^0.32.4",
-    "rollup-plugin-buble": "^0.12.1"
+    "eslint": "^4.6.1",
+    "mocha": "^3.5.0",
+    "rollup": "^0.49.2",
+    "rollup-plugin-buble": "^0.15.0"
   },
   "main": "dist/rollup-plugin-replace.cjs.js",
-  "jsnext:main": "dist/rollup-plugin-replace.es.js",
+  "module": "dist/rollup-plugin-replace.es.js",
   "dependencies": {
-    "magic-string": "^0.15.2",
+    "magic-string": "^0.22.4",
     "minimatch": "^3.0.2",
-    "rollup-pluginutils": "^1.5.0"
+    "rollup-pluginutils": "^2.0.1"
   },
   "scripts": {
     "test": "mocha",
     "pretest": "npm run build",
-    "build": "rollup -c -f cjs -o dist/rollup-plugin-replace.cjs.js && rollup -c -f es -o dist/rollup-plugin-replace.es.js",
+    "build": "rollup -c",
     "prebuild": "rm -rf dist/*",
     "prepublish": "npm test"
   },
@@ -26,10 +26,7 @@
     "dist",
     "README.md"
   ],
-  "repository": {
-    "type": "git",
-    "url": "git+https://github.com/rollup/rollup-plugin-replace.git"
-  },
+  "repository": "rollup/rollup-plugin-replace",
   "keywords": [
     "rollup",
     "rollup-plugin",
diff --git a/rollup.config.js b/rollup.config.js
index cc033ad..da50725 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -1,9 +1,14 @@
 import buble from 'rollup-plugin-buble';
+import pkg from './package.json';
 
-var external = Object.keys( require( './package.json' ).dependencies ).concat( 'path' );
+var external = Object.keys(pkg.dependencies).concat('path');
 
 export default {
-	entry: 'src/index.js',
+	input: 'src/index.js',
 	plugins: [ buble() ],
-	external: external
+	external,
+	output: [
+		{ file: pkg.main, format: 'cjs' },
+		{ file: pkg.module, format: 'es' }
+	]
 };
diff --git a/src/index.js b/src/index.js
index be9258b..8811d30 100644
--- a/src/index.js
+++ b/src/index.js
@@ -1,43 +1,78 @@
 import MagicString from 'magic-string';
 import { createFilter } from 'rollup-pluginutils';
 
-function escape ( str ) {
-	return str.replace( /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&' );
+function escape(str) {
+	return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
 }
 
-export default function replace ( options = {} ) {
-	const values = options.values || options;
-	const delimiters = ( options.delimiters || [ '', '' ] ).map( escape );
-	const pattern = new RegExp( delimiters[0] + '(' + Object.keys( values ).join( '|' ) + ')' + delimiters[1], 'g' );
+function functor(thing) {
+	if (typeof thing === 'function') return thing;
+	return () => thing;
+}
+
+function longest(a, b) {
+	return b.length - a.length;
+}
+
+export default function replace(options = {}) {
+	const filter = createFilter(options.include, options.exclude);
+	const { delimiters } = options;
+
+	let values;
+
+	if (options.values) {
+		values = options.values;
+	} else {
+		values = Object.assign({}, options);
+		delete values.delimiters;
+		delete values.include;
+		delete values.exclude;
+	}
+
+	const keys = Object.keys(values).sort(longest).map(escape);
+
+	const pattern = delimiters ?
+		new RegExp(
+			`${escape(delimiters[0])}(${keys.join('|')})${escape(delimiters[1])}`,
+			'g'
+		) :
+		new RegExp(
+			`\\b(${keys.join('|')})\\b`,
+			'g'
+		);
 
-	const filter = createFilter( options.include, options.exclude );
+	// convert all values to functions
+	Object.keys(values).forEach(key => {
+		values[key] = functor(values[key]);
+	});
 
 	return {
 		name: 'replace',
 
-		transform ( code, id ) {
-			if ( !filter( id ) ) return null;
+		transform(code, id) {
+			if (!filter(id)) return null;
 
-			const magicString = new MagicString( code );
+			const magicString = new MagicString(code);
 
 			let hasReplacements = false;
 			let match;
 			let start, end, replacement;
 
-			while ( match = pattern.exec( code ) ) {
+			while ((match = pattern.exec(code))) {
 				hasReplacements = true;
 
 				start = match.index;
 				end = start + match[0].length;
-				replacement = String( values[ match[1] ] );
+				replacement = String(values[match[1]](id));
 
-				magicString.overwrite( start, end, replacement );
+				magicString.overwrite(start, end, replacement);
 			}
 
-			if ( !hasReplacements ) return null;
+			if (!hasReplacements) return null;
 
 			let result = { code: magicString.toString() };
-			if ( options.sourceMap !== false ) result.map = magicString.generateMap({ hires: true });
+			if (options.sourceMap !== false && options.sourcemap !== false)
+				result.map = magicString.generateMap({ hires: true });
 
 			return result;
 		}
diff --git a/test/index.js b/test/index.js
deleted file mode 100644
index 406f6dd..0000000
--- a/test/index.js
+++ /dev/null
@@ -1,25 +0,0 @@
-var assert = require( 'assert' );
-var rollup = require( 'rollup' );
-var replace = require( '..' );
-
-process.chdir( __dirname );
-
-describe( 'rollup-plugin-replace', function () {
-	it( 'replaces strings', function () {
-		return rollup.rollup({
-			entry: 'samples/basic/main.js',
-			plugins: [
-				replace({
-					ENV: "'production'"
-				})
-			]
-		}).then( function ( bundle ) {
-			const generated = bundle.generate();
-			const code = generated.code;
-
-			assert.ok( code.indexOf( "'production' !== 'production'" ) !== -1 );
-		});
-	});
-
-	// TODO tests for delimiters, sourcemaps, etc
-});
diff --git a/test/samples/basic/main.js b/test/samples/basic/main.js
index c48e748..2dbcae8 100644
--- a/test/samples/basic/main.js
+++ b/test/samples/basic/main.js
@@ -1,5 +1 @@
-if ( ENV !== 'production' ) {
-	console.log( 'running in debug mode...' );
-} else {
-	console.log( 'running...' );
-}
+console.log(ANSWER);
\ No newline at end of file
diff --git a/test/samples/boundaries/main.js b/test/samples/boundaries/main.js
new file mode 100644
index 0000000..1724715
--- /dev/null
+++ b/test/samples/boundaries/main.js
@@ -0,0 +1,2 @@
+export const foo = 'unchanged';
+export const bar = 'changed';
\ No newline at end of file
diff --git a/test/samples/longest-first/main.js b/test/samples/longest-first/main.js
new file mode 100644
index 0000000..ccf78a9
--- /dev/null
+++ b/test/samples/longest-first/main.js
@@ -0,0 +1 @@
+console.log('BUILD version BUILD_VERSION');
\ No newline at end of file
diff --git a/test/samples/relative/dir/foo.js b/test/samples/relative/dir/foo.js
new file mode 100644
index 0000000..9193a37
--- /dev/null
+++ b/test/samples/relative/dir/foo.js
@@ -0,0 +1 @@
+export default __filename;
diff --git a/test/samples/relative/main.js b/test/samples/relative/main.js
new file mode 100644
index 0000000..749a861
--- /dev/null
+++ b/test/samples/relative/main.js
@@ -0,0 +1,5 @@
+import foo from './dir/foo.js';
+
+var bar = __filename;
+
+export { foo, bar };
diff --git a/test/samples/special-chars/main.js b/test/samples/special-chars/main.js
new file mode 100644
index 0000000..ea4b851
--- /dev/null
+++ b/test/samples/special-chars/main.js
@@ -0,0 +1,2 @@
+const one = require('one');
+console.log(one);
\ No newline at end of file
diff --git a/test/test.js b/test/test.js
new file mode 100644
index 0000000..d1ef5be
--- /dev/null
+++ b/test/test.js
@@ -0,0 +1,100 @@
+const assert = require('assert');
+const path = require('path');
+const { rollup } = require('rollup');
+const replace = require('../dist/rollup-plugin-replace.cjs.js');
+
+process.chdir( __dirname );
+
+async function evaluate(sample, opts) {
+	const bundle = await rollup({
+		input: `samples/${sample}/main.js`,
+		plugins: [
+			replace(opts)
+		]
+	});
+
+	const { code } = await bundle.generate({ format: 'cjs' });
+	const fn = new Function('module', 'exports', code);
+	const module = { exports: {} };
+	fn(module, module.exports);
+
+	return module.exports;
+}
+
+describe('rollup-plugin-replace', () => {
+	it('replaces strings', async () => {
+		const bundle = await rollup({
+			input: 'samples/basic/main.js',
+			plugins: [
+				replace({
+					ANSWER: '42'
+				})
+			]
+		});
+
+		const { code } = await bundle.generate({ format: 'es' });
+		assert.equal(code.trim(), 'console.log(42);');
+	});
+
+	it('allows replacement to be a function', async () => {
+		const bundle = await rollup({
+			input: 'samples/relative/main.js',
+			plugins: [
+				replace({
+					__filename: id => JSON.stringify(id.slice(path.resolve(__dirname, 'samples/relative').length + 1))
+				})
+			]
+		});
+
+		const { code } = await bundle.generate({ format: 'cjs' });
+
+		const fn = new Function('module', 'exports', code);
+		const module = { exports: {} };
+		fn(module, module.exports);
+
+		assert.equal(module.exports.foo, path.join('dir', 'foo.js'));
+		assert.equal(module.exports.bar, 'main.js');
+	});
+
+	it('matches most specific variables', async () => {
+		const bundle = await rollup({
+			input: 'samples/longest-first/main.js',
+			plugins: [
+				replace({
+					BUILD: 'beta',
+					BUILD_VERSION: '1.0.0'
+				})
+			]
+		})
+
+		const { code } = await bundle.generate({ format: 'es' });
+
+		assert.equal(code.trim(), `console.log('beta version 1.0.0');`);
+	});
+
+	it('supports special characters' , async () => {
+		const bundle = await rollup({
+			input: 'samples/special-chars/main.js',
+			plugins: [
+				replace({
+					"require('one')": "1",
+					delimiters: ['', '']
+				})
+			]
+		});
+
+		const { code } = await bundle.generate({ format: 'es' });
+		assert.equal(code.trim(), 'const one = 1;\nconsole.log(one);');
+	});
+
+	it('uses word boundaries if delimiters are unspecified', async () => {
+		const exports = await evaluate('boundaries', { changed: 'replaced' });
+
+		assert.deepEqual(exports, {
+			foo: 'unchanged',
+			bar: 'replaced'
+		});
+	});
+
+	// TODO tests for delimiters, sourcemaps, etc
+});

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-rollup-plugin-replace.git



More information about the Pkg-javascript-commits mailing list