Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support multiple previewjs config extensions and add defineConfig() helper #2086

Merged
merged 6 commits into from
Oct 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions config/build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,7 @@ export default {
externals: ["vite"],
declaration: true,
clean: true,
rollup: {
emitCJS: true,
},
};
17 changes: 13 additions & 4 deletions config/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,26 @@
"url": "https://github.com/fwouts/previewjs/issues"
},
"homepage": "https://previewjs.com",
"type": "module",
"main": "./dist/index.mjs",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"require": "./dist/index.cjs",
"import": "./dist/index.mjs",
"types": "./dist/index.d.ts"
}
},
"sideEffects": false,
"scripts": {
"build": "tsc && unbuild"
},
"dependencies": {
"vite": "^4.4.11"
},
"devDependencies": {
"@types/node": "^20.8.2",
"typescript": "^5.2.2",
"unbuild": "^2.0.0",
"vite": "^4.4.11"
"unbuild": "^2.0.0"
}
}
10 changes: 9 additions & 1 deletion config/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import type { UserConfig } from "vite";

export function defineConfig(config: PreviewConfig) {
return {
// Note: this can be removed after Feb 2024.
publicDir: "public",
...config,
};
}

export interface PreviewConfig {
/** @deprecated Use the `vite.resolve.alias` field instead. */
alias?: Record<string, string>;
publicDir: string;
publicDir?: string;
wrapper?: {
path: string;
componentName?: string;
Expand Down
3 changes: 2 additions & 1 deletion config/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { defineConfig } from "./config";
export type { PreviewConfig } from "./config";
export { PREVIEW_CONFIG_NAME, readConfig } from "./read-config";
export { PREVIEW_CONFIG_NAMES, readConfig } from "./read-config";
82 changes: 40 additions & 42 deletions config/src/read-config.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,51 @@
import fs from "fs";
import { createRequire } from "module";
import path from "path";
import url from "url";
import { loadConfigFromFile, type LogLevel } from "vite";
import type { PreviewConfig } from "./config";

const require = createRequire(import.meta.url);
export const PREVIEW_CONFIG_NAMES = [
"preview.config.js",
"preview.config.mjs",
"preview.config.ts",
"preview.config.cjs",
"preview.config.mts",
"preview.config.cts",
];

export const PREVIEW_CONFIG_NAME = "preview.config.js";

export async function readConfig(rootDir: string): Promise<PreviewConfig> {
const configPath = path.join(rootDir, PREVIEW_CONFIG_NAME);
export async function readConfig(
rootDir: string,
logLevel: LogLevel
): Promise<PreviewConfig> {
let config: Partial<PreviewConfig> = {};
const configFileExists = fs.existsSync(configPath);
if (configFileExists) {
let isModule = false;
const packageJsonPath = path.join(rootDir, "package.json");
if (fs.existsSync(packageJsonPath)) {
const { type } = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
isModule = type === "module";
}
try {
return await loadModule(configPath, isModule);
} catch (e) {
// Try again but with the other type of module.
for (const configName of PREVIEW_CONFIG_NAMES) {
const configPath = path.join(rootDir, configName);
const configFileExists = fs.existsSync(configPath);
if (configFileExists) {
try {
return await loadModule(configPath, !isModule);
} catch {
// Throw the original error if not working.
throw new Error(`Unable to read preview.config.js:\n${e}`);
const loaded = await loadConfigFromFile(
{
command: "serve",
mode: "development",
},
configName,
rootDir,
logLevel
);
if (loaded) {
config = loaded.config as Partial<PreviewConfig>;
break;
}
} catch (e: any) {
if (
typeof e.message === "string" &&
e.message.includes("config must export or return an object")
) {
throw new Error(`Please use a default export in preview.config.js`);
} else {
throw e;
}
}
}
}
return {
alias: {},
publicDir: "public",
...config,
};
}

async function loadModule(configPath: string, asModule: boolean) {
if (asModule) {
const module = await import(
`${url.pathToFileURL(configPath).href}?ts=${Date.now()}`
);
return module.default || module;
} else {
// Delete any existing cache so we reload the config fresh.
delete require.cache[require.resolve(configPath)];
const required = require(configPath);
return required.module || required;
}
return config;
}
15 changes: 8 additions & 7 deletions core/src/html-error.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
import { escape } from "html-escaper";

export function generateHtmlError(message: string) {
if (message.startsWith("Error: Build failed with 1 error:\n")) {
message = message.substring(message.indexOf("\n") + 1);
}
return `<html>
<head>
<meta http-equiv="refresh" content="3">
<style>
body {
background: #FCA5A5
}
pre {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
white-space: pre-wrap;
background: #FCA5A5;
color: #7F1D1D;
margin: 8px;
font-size: 12px;
line-height: 1.5em;
color: #7F1D1D;
}
</style>
</head>
<body>
<pre>${escape(message)}</pre>
</body>
<body>${escape(message.trim())}</body>
</html>`;
}
12 changes: 8 additions & 4 deletions core/src/vite/vite-manager.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import viteTsconfigPaths from "@fwouts/vite-tsconfig-paths";
import { decodePreviewableId } from "@previewjs/analyzer-api";
import {
PREVIEW_CONFIG_NAME,
PREVIEW_CONFIG_NAMES,
readConfig,
type PreviewConfig,
} from "@previewjs/config";
Expand Down Expand Up @@ -62,7 +62,7 @@ const GLOBAL_CSS_FILE = GLOBAL_CSS_FILE_NAMES_WITHOUT_EXT.flatMap((fileName) =>
);

const FILES_REQUIRING_VITE_RESTART = new Set([
PREVIEW_CONFIG_NAME,
...PREVIEW_CONFIG_NAMES,
...FILES_REQUIRING_REDETECTION,
...POSTCSS_CONFIG_FILE,
...GLOBAL_CSS_FILE,
Expand Down Expand Up @@ -251,7 +251,10 @@ export class ViteManager {
// PostCSS requires the current directory to change because it relies
// on the `import-cwd` package to resolve plugins.
process.chdir(this.options.rootDir);
const configFromProject = await readConfig(this.options.rootDir);
const configFromProject = await readConfig(
this.options.rootDir,
viteLogLevelFromPinoLogger(this.options.logger)
);
const globalCssAbsoluteFilePaths = await findFiles(
this.options.rootDir,
`**/@(${GLOBAL_CSS_FILE_NAMES_WITHOUT_EXT.join(
Expand Down Expand Up @@ -353,7 +356,8 @@ export class ViteManager {
config.vite?.publicDir ||
existingViteConfig?.config.publicDir ||
frameworkPluginViteConfig.publicDir ||
config.publicDir;
config.publicDir ||
"public";
const plugins = replaceHandleHotUpdate(
this.options.reader,
await flattenPlugins([
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
{
"name": "react-test-app-wrapper-custom-esm-named-exports-config",
"name": "react-test-app-wrapper-custom-config-ts",
"license": "MIT",
"private": true,
"type": "module",
"scripts": {
"start": "react-scripts start"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/** @type {import("@previewjs/config").PreviewConfig} */
export default {
wrapper: {
path: "src/Wrapper.js",
componentName: "Around",
},
};

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/** @type {import("@previewjs/config").PreviewConfig} */
export default {
import { defineConfig } from "@previewjs/config";

export default defineConfig({
wrapper: {
path: "src/Wrapper.js",
componentName: "Around",
},
};
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/** @type {import("@previewjs/config").PreviewConfig} */
module.exports = {
import { defineConfig } from "@previewjs/config";

export default defineConfig({
wrapper: {
path: "src/Wrapper.js",
componentName: "Around",
},
};
});
2 changes: 1 addition & 1 deletion framework-plugins/react/tests/smoke-tests.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ test.describe.parallel("smoke tests", () => {
"vite-without-svgr": ["src/App.tsx:App"],
"wrapper-custom": ["src/App.tsx:App"],
"wrapper-custom-esm": ["src/App.tsx:App"],
"wrapper-custom-esm-named-exports-config": ["src/App.tsx:App"],
"wrapper-custom-config-ts": ["src/App.tsx:App"],
"wrapper-default": ["src/App.tsx:App"],
},
});
Expand Down
Loading