Skip to content

Commit

Permalink
Fix parsing spread operator on require() (#2)
Browse files Browse the repository at this point in the history
* Add test for using the spread operator on `require()`

* Fix typo in spread operator test

* Check if `require()` is preceded by a spread operator

Updated test to check both spreading inside an array and an object.
  • Loading branch information
lejeunerenard authored Jan 3, 2025
1 parent 289308f commit edaedea
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
7 changes: 6 additions & 1 deletion sloppy-require-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function parseCJS (src, result) {
continue
}

if (newWord(src, i) && !inComment(src, i)) {
if ((newWord(src, i) || isSpread(src, i)) && !inComment(src, i)) {
const suffix = src.slice(i + 7)
const m = suffix.match(CALL_WITH_STRING)

Expand Down Expand Up @@ -60,6 +60,11 @@ function newWord (src, i) {
return !/^\w|["'`._]/.test(s)
}

function isSpread (src, i) {
const s = i > 0 ? src.slice(i - 3, i) : ''
return s === '...'
}

function inComment (src, i) {
const pre = src.slice(i > 100 ? i - 100 : 0, i)
return pre.indexOf('//', Math.max(pre.lastIndexOf('\n'), 0)) > -1 && src.slice(i, i + 100).indexOf('\n') > -1
Expand Down
13 changes: 13 additions & 0 deletions test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,19 @@ test('basic module', function (t) {
t.alike(res.resolutions.map(r => r.input), ['world', 'dynamic'])
})

test('spread require output', function (t) {
const res = parse(`
const b = [...require("./def/pear" )]
const c = { ...require("./obj" ) }
const d = {
...require("./newline-obj" )
}
`, 'script')

t.is(res.type, 'script')
t.alike(res.resolutions.map(r => r.input), ['./def/pear', './obj', './newline-obj'])
})

test('script that falls back', function (t) {
const res = parse(`
import hello from 'world'
Expand Down

0 comments on commit edaedea

Please sign in to comment.