Skip to content

Commit

Permalink
fix: forward vite plugin config to esbuild plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
DylanPiercey committed Apr 25, 2022
1 parent 773b6e7 commit f28ed5b
Show file tree
Hide file tree
Showing 3 changed files with 132 additions and 159 deletions.
96 changes: 96 additions & 0 deletions src/esbuild-plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import fs from "fs";
import path from "path";
import type * as esbuild from "esbuild";
import type * as Compiler from "@marko/compiler";

const markoErrorRegExp = /^(.+?)(?:\((\d+)(?:\s*,\s*(\d+))?\))?: (.*)$/gm;

export default function esbuildPlugin(
compiler: typeof Compiler,
config: Compiler.Config
): esbuild.Plugin {
return {
name: "marko",
async setup(build) {
const { platform = "browser" } = build.initialOptions;
const virtualFiles = new Map<string, { code: string; map?: unknown }>();
const finalConfig: Compiler.Config = {
...config,
output: platform === "browser" ? "dom" : "html",
resolveVirtualDependency(from, dep) {
virtualFiles.set(path.join(from, "..", dep.virtualPath), dep);
return dep.virtualPath;
},
};

if (platform === "browser") {
build.onResolve({ filter: /\.marko\./ }, (args) => {
return {
namespace: "marko:virtual",
path: path.resolve(args.resolveDir, args.path),
};
});

build.onLoad(
{ filter: /\.marko\./, namespace: "marko:virtual" },
(args) => ({
contents: virtualFiles.get(args.path)!.code,
loader: path.extname(args.path).slice(1) as esbuild.Loader,
})
);

build.onResolve({ filter: /\.marko$/ }, async (args) => ({
namespace: "file",
path: path.resolve(args.resolveDir, args.path),
}));
}

build.onLoad({ filter: /\.marko$/, namespace: "file" }, async (args) => {
try {
const { code, meta } = await compiler.compileFile(
args.path,
finalConfig
);

return {
loader: "js",
contents: code,
watchFiles: meta.watchFiles,
resolveDir: path.dirname(args.path),
};
} catch (e) {
const text = (e as Error).message;
const errors: esbuild.PartialMessage[] = [];
let match: RegExpExecArray | null;
let lines: string[] | undefined;

while ((match = markoErrorRegExp.exec(text))) {
const [, file, rawLine, rawCol, text] = match;
const line = parseInt(rawLine, 10) || 1;
const column = parseInt(rawCol, 10) || 1;
lines ||= (await fs.promises.readFile(args.path, "utf-8")).split(
/\n/g
);
errors.push({
text,
location: {
file,
line,
column,
lineText: ` ${lines[line - 1]}`,
},
});
}

if (!errors.length) {
errors.push({ text });
}

return {
errors,
};
}
});
},
};
}
58 changes: 36 additions & 22 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
generateDocManifest,
DocManifest,
} from "./manifest-generator";
import esbuildPlugin from "./marko-plugin";
import esbuildPlugin from "./esbuild-plugin";

export interface Options {
// Defaults to true, set to false to disable automatic component discovery and hydration.
Expand Down Expand Up @@ -52,6 +52,7 @@ const virtualFileQuery = "?marko-virtual";
const markoExt = ".marko";
const htmlExt = ".html";
const resolveOpts = { skipSelf: true };
const cache = new Map<string, Compiler.CompileResult>();
const thisFile =
typeof __filename === "string" ? __filename : fileURLToPath(import.meta.url);
let tempDir: Promise<string> | undefined;
Expand All @@ -61,10 +62,10 @@ export default function markoPlugin(opts: Options = {}): vite.Plugin[] {
const { runtimeId, linked = true } = opts;

const baseConfig: Compiler.Config = {
cache,
runtimeId,
sourceMaps: true,
writeVersionComment: false,
cache: new Map<string, Compiler.CompileResult>(),
babelConfig: {
...opts.babelConfig,
caller: {
Expand All @@ -76,38 +77,45 @@ export default function markoPlugin(opts: Options = {}): vite.Plugin[] {
...opts.babelConfig?.caller,
},
},
resolveVirtualDependency(from, dep) {
const query = `${virtualFileQuery}&id=${encodeURIComponent(
dep.virtualPath
)}`;
const id = normalizePath(from) + query;

if (devServer) {
const prev = virtualFiles.get(id);
if (prev && prev.code !== dep.code) {
devServer.moduleGraph.invalidateModule(
devServer.moduleGraph.getModuleById(id)!
);
}
};

const resolveViteVirtualDep: Compiler.Config["resolveVirtualDependency"] = (
from,
dep
) => {
const query = `${virtualFileQuery}&id=${encodeURIComponent(
dep.virtualPath
)}`;
const id = normalizePath(from) + query;

if (devServer) {
const prev = virtualFiles.get(id);
if (prev && prev.code !== dep.code) {
devServer.moduleGraph.invalidateModule(
devServer.moduleGraph.getModuleById(id)!
);
}
}

virtualFiles.set(id, dep);
return `./${path.basename(from) + query}`;
},
virtualFiles.set(id, dep);
return `./${path.basename(from) + query}`;
};

const ssrConfig: Compiler.Config = {
...baseConfig,
resolveVirtualDependency: resolveViteVirtualDep,
output: "html",
};

const domConfig: Compiler.Config = {
...baseConfig,
resolveVirtualDependency: resolveViteVirtualDep,
output: "dom",
};

const hydrateConfig: Compiler.Config = {
...domConfig,
...baseConfig,
resolveVirtualDependency: resolveViteVirtualDep,
output: "hydrate",
};

Expand Down Expand Up @@ -196,10 +204,16 @@ export default function markoPlugin(opts: Options = {}): vite.Plugin[] {
...config,
optimizeDeps: {
...config.optimizeDeps,
extensions: [...(config?.optimizeDeps?.extensions || []), ".marko"],
extensions: [
".marko",
...((config.optimizeDeps as any)?.extensions || []),
],
esbuildOptions: {
plugins: [esbuildPlugin()],
} as any,
plugins: [
esbuildPlugin(compiler, baseConfig),
...(config.optimizeDeps?.esbuildOptions?.plugins || []),
],
},
},
};
},
Expand Down
137 changes: 0 additions & 137 deletions src/marko-plugin.ts

This file was deleted.

0 comments on commit f28ed5b

Please sign in to comment.