Skip to content

Commit

Permalink
fix(replace): prevent variable before colons from being replaced when…
Browse files Browse the repository at this point in the history
… preventAssigment is true (#1609)

* fix: prevent variable before colons from being replaced when preventAssignment is true.

* feat: add typescript-declare test.

---------

Co-authored-by: huanghao36 <huanghao10@jd.com>
  • Loading branch information
hhgnsc and huanghao36 committed Oct 29, 2023
1 parent 4f9fc5a commit 047d21c
Show file tree
Hide file tree
Showing 7 changed files with 24 additions and 3 deletions.
2 changes: 1 addition & 1 deletion packages/replace/src/index.js
Expand Up @@ -74,7 +74,7 @@ export default function replace(options = {}) {
if (objectGuards) expandTypeofReplacements(replacements);
const functionValues = mapToFunctions(replacements);
const keys = Object.keys(functionValues).sort(longest).map(escape);
const lookahead = preventAssignment ? '(?!\\s*=[^=])' : '';
const lookahead = preventAssignment ? '(?!\\s*(=[^=]|:[^:]))' : '';
const pattern = new RegExp(
`${delimiters[0]}(${keys.join('|')})${delimiters[1]}${lookahead}`,
'g'
Expand Down
@@ -0,0 +1,8 @@
module.exports = {
description: "doesn't replace lvalue in typescript declare",
isTypescript: true,
options: {
'NAME': 'replaced',
preventAssignment: true
}
};
@@ -0,0 +1,2 @@
declare const NAME: string
console.log(NAME)
@@ -0,0 +1,3 @@
// eslint-disable-next-line @typescript-eslint/no-unused-vars
declare const NAME: string
console.log('replaced')
5 changes: 3 additions & 2 deletions packages/replace/test/form.js
Expand Up @@ -21,10 +21,11 @@ readdirSync('./fixtures/form').forEach((dir) => {

test(`${dir}: ${config.description}`, (t) => {
const { transform } = replace(config.options);
const input = readFileSync(`fixtures/form/${dir}/input.js`, 'utf-8');
const extname = config.isTypescript ? 'ts' : 'js';
const input = readFileSync(`fixtures/form/${dir}/input.${extname}`, 'utf-8');

return Promise.resolve(
transform.call(transformContext, input, `${__dirname}/fixtures/form/${dir}/input.js`)
transform.call(transformContext, input, `${__dirname}/fixtures/form/${dir}/input.${extname}`)
).then((transformed) => {
const actual = (transformed ? transformed.code : input).trim();
t.snapshot(actual);
Expand Down
7 changes: 7 additions & 0 deletions packages/replace/test/snapshots/form.js.md
Expand Up @@ -86,3 +86,10 @@ Generated by [AVA](https://avajs.dev).
especial␊
replaced.doSomething()␊
\`);`

## typescript-declare: doesn't replace lvalue in typescript declare

> Snapshot 1
`declare const NAME: string␊
console.log(replaced)`
Binary file modified packages/replace/test/snapshots/form.js.snap
Binary file not shown.

0 comments on commit 047d21c

Please sign in to comment.