Skip to content

Commit cfb4555

Browse files
authored
fix(inject): escape metacharacters in module name string (#897)
* test(inject): should escape apostrophe or backslash in module name * fix(inject): escape apostrophes and backslashes in module name * test(inject): disable non-portable test on Windows
1 parent a0243b1 commit cfb4555

File tree

4 files changed

+40
-2
lines changed

4 files changed

+40
-2
lines changed

packages/inject/src/index.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -133,10 +133,12 @@ export default function inject(options) {
133133
name === keypath ? name : makeLegalIdentifier(`$inject_${keypath}`);
134134

135135
if (!newImports.has(hash)) {
136+
// escape apostrophes and backslashes for use in single-quoted string literal
137+
const modName = mod[0].replace(/[''\\]/g, '\\$&');
136138
if (mod[1] === '*') {
137-
newImports.set(hash, `import * as ${importLocalName} from '${mod[0]}';`);
139+
newImports.set(hash, `import * as ${importLocalName} from '${modName}';`);
138140
} else {
139-
newImports.set(hash, `import { ${mod[1]} as ${importLocalName} } from '${mod[0]}';`);
141+
newImports.set(hash, `import { ${mod[1]} as ${importLocalName} } from '${modName}';`);
140142
}
141143
}
142144

packages/inject/test/snapshots/test.js.md

+22
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,28 @@ Generated by [AVA](https://avajs.dev).
2626
});␊
2727
`
2828

29+
## escapes apostrophes in module name
30+
31+
> Snapshot 1
32+
33+
`import { default as $ } from 'd\\'oh';␊
34+
35+
$(() => {␊
36+
console.log('ready');␊
37+
});␊
38+
`
39+
40+
## escapes backslashes in module name
41+
42+
> Snapshot 1
43+
44+
`import { default as $ } from 'slash\\\\back';␊
45+
46+
$(() => {␊
47+
console.log('ready');␊
48+
});␊
49+
`
50+
2951
## inserts a named import statement
3052

3153
> Snapshot 1
72 Bytes
Binary file not shown.

packages/inject/test/test.js

+14
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
const fs = require('fs');
22
const path = require('path');
3+
const os = require('os');
34

45
const acorn = require('acorn');
56
const test = require('ava');
@@ -34,6 +35,19 @@ test('uses the modules property', (t) => {
3435
});
3536
});
3637

38+
test('escapes apostrophes in module name', (t) => {
39+
compare(t, 'basic', { $: "d'oh" });
40+
});
41+
42+
if (os.platform() === 'win32') {
43+
// backslash is path separator on Windows,
44+
// so it cannot appear within filename
45+
} else {
46+
test('escapes backslashes in module name', (t) => {
47+
compare(t, 'basic', { $: 'slash\\back' });
48+
});
49+
}
50+
3751
test('inserts a named import statement', (t) => {
3852
compare(t, 'named', { Promise: ['es6-promise', 'Promise'] });
3953
});

0 commit comments

Comments
 (0)