Skip to content

Commit

Permalink
feat: enable auto imports from utils dir (#866)
Browse files Browse the repository at this point in the history
* feat: enable auto imports from `utils` dir

* update test

* update fixture

* try with #imports

* fix: avoid hiding original rollup error message

* fix: enable `virtualImports`

* fix: manually inject dir imports as dynamic imports

* refactor: simplify

* simplify

Co-authored-by: Anthony Fu <[email protected]>
  • Loading branch information
pi0 and antfu authored Jan 23, 2023
1 parent d0ab926 commit 724c709
Show file tree
Hide file tree
Showing 6 changed files with 46 additions and 8 deletions.
9 changes: 9 additions & 0 deletions src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import * as rollup from "rollup";
import fse from "fs-extra";
import { defu } from "defu";
import { watch } from "chokidar";
import { scanDirExports } from "unimport";
import { debounce } from "perfect-debounce";
import type { TSConfig } from "pkg-types";
import type { RollupError } from "rollup";
import type { OnResolveResult, PartialMessage } from "esbuild";
import type { RouterMethod } from "h3";
import { i } from "vitest/dist/index-50755efe";
import { generateFSTree } from "./utils/tree";
import { getRollupConfig, RollupConfig } from "./rollup/config";
import { prettyPath, writeFile, isDirectory } from "./utils";
Expand Down Expand Up @@ -94,6 +96,13 @@ export async function writeTypes(nitro: Nitro) {
let autoImportedTypes: string[] = [];

if (nitro.unimport) {
await nitro.unimport.modifyDynamicImports(async () => {
const { dirs } = nitro.options.imports as { dirs: string[] };
return (await scanDirExports(dirs)).map((i) => ({
...i,
from: i.from.replace(/\.ts$/, ""),
}));
});
autoImportedTypes = [
(
await nitro.unimport.generateTypeDeclarations({
Expand Down
1 change: 1 addition & 0 deletions src/nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ export async function createNitro(config: NitroConfig = {}): Promise<Nitro> {
}
}

// Auto imports
if (nitro.options.imports) {
nitro.unimport = createUnimport(nitro.options.imports);
// Support for importing from '#imports'
Expand Down
17 changes: 13 additions & 4 deletions src/options.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { resolve, join, normalize } from "pathe";
import { resolve, join } from "pathe";
import { loadConfig } from "c12";
import { klona } from "klona/full";
import { camelCase } from "scule";
Expand Down Expand Up @@ -44,7 +44,9 @@ const NitroDefaults: NitroConfig = {
plugins: [],
imports: {
exclude: [],
dirs: [],
presets: nitroImports,
virtualImports: ["#imports"],
},
virtual: {},
compressPublicAssets: false,
Expand Down Expand Up @@ -186,12 +188,12 @@ export async function loadOptions(
),
];

if (options.scanDirs.length === 0) {
options.scanDirs = [options.srcDir];
}
// Resolve scanDirs
options.scanDirs.unshift(options.srcDir);
options.scanDirs = options.scanDirs.map((dir) =>
resolve(options.srcDir, dir)
);
options.scanDirs = [...new Set(options.scanDirs)];

if (
options.imports &&
Expand Down Expand Up @@ -228,6 +230,13 @@ export async function loadOptions(
});
}

// Auto imports from utils dirs
if (options.imports) {
options.imports.dirs.push(
...options.scanDirs.map((dir) => join(dir, "utils/*"))
);
}

// Backward compatibility for options.routes
options.routeRules = defu(options.routeRules, (options as any).routes || {});

Expand Down
5 changes: 5 additions & 0 deletions test/fixture/routes/imports.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default defineEventHandler(() => {
return {
testUtil: testUtil(),
};
});
1 change: 1 addition & 0 deletions test/fixture/utils/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const testUtil = () => 123;
21 changes: 17 additions & 4 deletions test/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,12 +203,16 @@ export function testNitro(
});

it("handles custom server assets", async () => {
const { data: html, status: htmlStatus } = await callHandler({ url: "/file?filename=index.html" });
const { data: txtFile, status: txtStatus } = await callHandler({ url: "/file?filename=test.txt" });
const { data: html, status: htmlStatus } = await callHandler({
url: "/file?filename=index.html",
});
const { data: txtFile, status: txtStatus } = await callHandler({
url: "/file?filename=test.txt",
});
expect(htmlStatus).toBe(200);
expect(html).toContain('<h1>nitro is amazing!</h1>');
expect(html).toContain("<h1>nitro is amazing!</h1>");
expect(txtStatus).toBe(200);
expect(txtFile).toContain('this is an asset from a text file from nitro');
expect(txtFile).toContain("this is an asset from a text file from nitro");
});

if (ctx.nitro!.options.serveStatic) {
Expand Down Expand Up @@ -237,6 +241,15 @@ export function testNitro(
expect(status).toBe(404);
});

it("find auto imported utils", async () => {
const res = await callHandler({ url: "/imports" });
expect(res.data).toMatchInlineSnapshot(`
{
"testUtil": 123,
}
`);
});

it("resolve module version conflicts", async () => {
const { data } = await callHandler({ url: "/modules" });
expect(data).toMatchObject({
Expand Down

0 comments on commit 724c709

Please sign in to comment.