Skip to content

Commit 047d21c

Browse files
hhgnschuanghao36
and
huanghao36
authored
fix(replace): prevent variable before colons from being replaced when 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>
1 parent 4f9fc5a commit 047d21c

File tree

7 files changed

+24
-3
lines changed

7 files changed

+24
-3
lines changed

packages/replace/src/index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ export default function replace(options = {}) {
7474
if (objectGuards) expandTypeofReplacements(replacements);
7575
const functionValues = mapToFunctions(replacements);
7676
const keys = Object.keys(functionValues).sort(longest).map(escape);
77-
const lookahead = preventAssignment ? '(?!\\s*=[^=])' : '';
77+
const lookahead = preventAssignment ? '(?!\\s*(=[^=]|:[^:]))' : '';
7878
const pattern = new RegExp(
7979
`${delimiters[0]}(${keys.join('|')})${delimiters[1]}${lookahead}`,
8080
'g'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module.exports = {
2+
description: "doesn't replace lvalue in typescript declare",
3+
isTypescript: true,
4+
options: {
5+
'NAME': 'replaced',
6+
preventAssignment: true
7+
}
8+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
declare const NAME: string
2+
console.log(NAME)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
2+
declare const NAME: string
3+
console.log('replaced')

packages/replace/test/form.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,11 @@ readdirSync('./fixtures/form').forEach((dir) => {
2121

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

2627
return Promise.resolve(
27-
transform.call(transformContext, input, `${__dirname}/fixtures/form/${dir}/input.js`)
28+
transform.call(transformContext, input, `${__dirname}/fixtures/form/${dir}/input.${extname}`)
2829
).then((transformed) => {
2930
const actual = (transformed ? transformed.code : input).trim();
3031
t.snapshot(actual);

packages/replace/test/snapshots/form.js.md

+7
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,10 @@ Generated by [AVA](https://avajs.dev).
8686
especial␊
8787
replaced.doSomething()␊
8888
\`);`
89+
90+
## typescript-declare: doesn't replace lvalue in typescript declare
91+
92+
> Snapshot 1
93+
94+
`declare const NAME: string␊
95+
console.log(replaced)`
42 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)