diff --git a/lib/index.js b/lib/index.js index 9512c13..66550c9 100644 --- a/lib/index.js +++ b/lib/index.js @@ -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: { diff --git a/package.json b/package.json index 8040596..3266b7e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "estree-util-build-jsx", - "version": "3.0.0", + "version": "3.0.1", "description": "Transform JSX in estrees to function calls (for react, preact, and most hyperscript interfaces)", "license": "MIT", "keywords": [ @@ -55,7 +55,7 @@ "remark-preset-wooorm": "^9.0.0", "type-coverage": "^2.0.0", "typescript": "^5.0.0", - "xo": "^0.55.0" + "xo": "^0.56.0" }, "scripts": { "prepack": "npm run build && npm run format", diff --git a/test.js b/test.js index 2120e39..ff5320a 100644 --- a/test.js +++ b/test.js @@ -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 = ') + + buildJsx(tree, {runtime: 'automatic'}) + + assert.equal( + generate(tree), + '"use client";\nimport {jsx as _jsx} from "react/jsx-runtime";\nconst x = _jsx("a", {});\n' + ) + }) }) /**