Skip to content

Commit ddf388c

Browse files
committed
Fix to keep directives before import statement
1 parent 2903133 commit ddf388c

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

lib/index.js

+13-1
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,19 @@ export function buildJsx(tree, options) {
216216
}
217217

218218
if (specifiers.length > 0) {
219-
node.body.unshift({
219+
let injectIndex = 0
220+
221+
while (injectIndex < node.body.length) {
222+
const child = node.body[injectIndex]
223+
224+
if ('directive' in child && child.directive) {
225+
injectIndex++
226+
} else {
227+
break
228+
}
229+
}
230+
231+
node.body.splice(injectIndex, 0, {
220232
type: 'ImportDeclaration',
221233
specifiers,
222234
source: {

test.js

+11
Original file line numberDiff line numberDiff line change
@@ -1647,6 +1647,17 @@ test('estree-util-build-jsx', async function (t) {
16471647
assert.equal(generate(tree), 'React.createElement("a");\n')
16481648
}
16491649
)
1650+
1651+
await t.test('should keep directives first', function () {
1652+
const tree = parse('"use client"\nconst x = <a/>')
1653+
1654+
buildJsx(tree, {runtime: 'automatic'})
1655+
1656+
assert.equal(
1657+
generate(tree),
1658+
'"use client";\nimport {jsx as _jsx} from "react/jsx-runtime";\nconst x = _jsx("a", {});\n'
1659+
)
1660+
})
16501661
})
16511662

16521663
/**

0 commit comments

Comments
 (0)