Skip to content

Commit

Permalink
Fix to keep directives before import statement
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Oct 22, 2023
1 parent 2903133 commit ddf388c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,19 @@ export function buildJsx(tree, options) {
}

if (specifiers.length > 0) {
node.body.unshift({
let injectIndex = 0

while (injectIndex < node.body.length) {
const child = node.body[injectIndex]

if ('directive' in child && child.directive) {
injectIndex++
} else {
break
}
}

node.body.splice(injectIndex, 0, {
type: 'ImportDeclaration',
specifiers,
source: {
Expand Down
11 changes: 11 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1647,6 +1647,17 @@ test('estree-util-build-jsx', async function (t) {
assert.equal(generate(tree), 'React.createElement("a");\n')
}
)

await t.test('should keep directives first', function () {
const tree = parse('"use client"\nconst x = <a/>')

buildJsx(tree, {runtime: 'automatic'})

assert.equal(
generate(tree),
'"use client";\nimport {jsx as _jsx} from "react/jsx-runtime";\nconst x = _jsx("a", {});\n'
)
})
})

/**
Expand Down

0 comments on commit ddf388c

Please sign in to comment.