Skip to content

Commit

Permalink
fix: various fixes to make baseweb working (tajo#24)
Browse files Browse the repository at this point in the history
* fix: various fixes to make baseweb working

* fix: use ESM for vite-plugin

* fix: meta.json, history, better errors

* fix: tests disabled temp, have to fix esm in jest

Co-authored-by: tajo <[email protected]>
  • Loading branch information
tajo and tajo authored Oct 27, 2021
1 parent c7fba31 commit 94519c3
Show file tree
Hide file tree
Showing 27 changed files with 353 additions and 175 deletions.
18 changes: 9 additions & 9 deletions lerna.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
"version": "independent",
"npmClientArgs": ["--no-lockfile"],
"command": {
"version": {
"ignoreChanges": ["*.md"],
"npmClient": "yarn",
"message": "chore(release): publish"
},
"publish": {
"npmClient": "npm",
"conventionalCommits": true
}
"version": {
"ignoreChanges": ["*.md"],
"npmClient": "yarn",
"message": "chore(release): publish [skip ci]"
},
"publish": {
"npmClient": "npm",
"conventionalCommits": true
}
}
}
1 change: 1 addition & 0 deletions packages/ladle/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export default {
preset: "ts-jest",
testEnvironment: "node",
transform: {},
};
3 changes: 1 addition & 2 deletions packages/ladle/lib/app/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ const App: React.FC<{}> = () => {
// handle go back/forward browser buttons
React.useEffect(() => {
// @ts-ignore
const unlisten = history.listen(({ action, location }) => {
console.log(action);
const unlisten = history.listen((location, action) => {
if (action === "POP") {
dispatch({
type: ActionType.UpdateAll,
Expand Down
15 changes: 14 additions & 1 deletion packages/ladle/lib/cli/build.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
#!/usr/bin/env node

import path from "path";
import { promises as fs } from "fs";
import globby from "globby";
import viteProd from "./vite-prod.js";
import loadConfig from "./load-config.js";
import debug from "./debug.js";
import { getMetaJsonString } from "./vite-plugin/generate/get-meta-json.js";
import { getEntryData } from "./vite-plugin/parse/get-entry-data.js";

/**
* @param params {import("../shared/types").BuildParams}
Expand Down Expand Up @@ -42,7 +46,16 @@ const build = async (params = {}) => {

debug(`Final config:\n${JSON.stringify(config, null, " ")}`);
process.env["VITE_PUBLIC_LADLE_THEME"] = config.addons.theme.defaultState;
return viteProd(config);
await viteProd(config, configFolder);
console.log("Creating meta.json file...");
const entryData = await getEntryData(await globby([config.stories]));
const jsonContent = getMetaJsonString(entryData);
await fs.writeFile(
path.join(process.cwd(), config.build.out, "meta.json"),
jsonContent,
);
console.log("meta.json file created.");
return true;
};

export default build;
2 changes: 1 addition & 1 deletion packages/ladle/lib/cli/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const serve = async (params = {}) => {

debug(`Final config:\n${JSON.stringify(config, null, " ")}`);
process.env["VITE_PUBLIC_LADLE_THEME"] = config.addons.theme.defaultState;
await viteDev(config);
await viteDev(config, configFolder);
};

export default serve;
41 changes: 41 additions & 0 deletions packages/ladle/lib/cli/vite-base.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import react from "@vitejs/plugin-react";
import ladlePlugin from "./vite-plugin/vite-plugin.js";

/**
* @param ladleConfig {import("../shared/types").Config}
* @param configFolder {string}
* @param viteConfig {import('vite').InlineConfig}
*/
const getBaseViteConfig = (ladleConfig, configFolder, viteConfig) => {
const __dirname = dirname(fileURLToPath(import.meta.url));
/**
* @type {import('vite').InlineConfig}
*/
const config = {
...viteConfig,
configFile: false,
root: join(__dirname, "../app/"),
base: ladleConfig.build.baseUrl,
plugins: [
ladlePlugin(ladleConfig, configFolder),
react({
babel: {
presets: ["@babel/preset-flow", ...ladleConfig.babelPresets],
plugins: ladleConfig.babelPlugins,
},
}),
...(viteConfig.plugins ? viteConfig.plugins : []),
],
esbuild: {
include: /\.(tsx?|jsx?)$/,
exclude: [],
loader: "tsx",
...(viteConfig.esbuild ? viteConfig.esbuild : {}),
},
};
return config;
};

export default getBaseViteConfig;
55 changes: 36 additions & 19 deletions packages/ladle/lib/cli/vite-dev.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,59 @@
import { createServer } from "vite";
import express from "express";
import getPort from "get-port";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import react from "@vitejs/plugin-react";
import ladlePlugin from "./vite-plugin/vite-plugin.js";
import globby from "globby";
import open from "open";
import debug from "./debug.js";
import getBaseViteConfig from "./vite-base.js";
import { getMetaJsonObject } from "./vite-plugin/generate/get-meta-json.js";
import { getEntryData } from "./vite-plugin/parse/get-entry-data.js";

/**
* @param config {import("../shared/types").Config}
* @param configFolder {string}
*/
const bundler = async (config) => {
const bundler = async (config, configFolder) => {
const app = express();
const port = await getPort({
port: [config.serve.port, 61001, 62002, 62003, 62004, 62005],
});
debug(`Port set to: ${port}`);
const __dirname = dirname(fileURLToPath(import.meta.url));
try {
/**
* @type {import('vite').InlineConfig}
*/
const viteConfig = {
configFile: false,
root: join(__dirname, "../app/"),
base: "/",
const viteConfig = getBaseViteConfig(config, configFolder, {
mode: "development",
plugins: [ladlePlugin(config), react()],
server: {
port: config.serve.port,
open: config.serve.open,
middlewareMode: "html",
},
esbuild: {
include: /\.(tsx?|jsx?)$/,
exclude: [],
loader: "tsx",
},
};
const server = await createServer(viteConfig);
await server.listen();
});
const vite = await createServer(viteConfig);
app.get("/meta.json", async (_, res) => {
const entryData = await getEntryData(await globby([config.stories]));
const jsonContent = getMetaJsonObject(entryData);
res.json(jsonContent);
});
app.use(vite.middlewares);
app.listen(port, async () => {
console.log("");
console.log("****************************************************");
console.log("");
console.log(` Ladle served at http://localhost:${port}`);
console.log("");
console.log("****************************************************");
console.log("");
if (config.serve.open !== "none") {
await open(
`http://localhost:${port}`,
["chrome", "firefox", "edge", "safari"].includes(config.serve.open)
? { app: { name: config.serve.open } }
: {},
);
}
});
} catch (e) {
console.log(e);
}
Expand Down
8 changes: 2 additions & 6 deletions packages/ladle/lib/cli/vite-plugin/ast-to-obj.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// nd-02110114/babel-plugin-object-to-json-parse
// https://github.com/nd-02110114/babel-plugin-object-to-json-parse/blob/master/src/utils.ts

const babelTypes = require("@babel/types");
import babelTypes from "@babel/types";
const {
isArrayExpression,
isBooleanLiteral,
Expand Down Expand Up @@ -77,7 +77,7 @@ const createSafeStringForJsonParse = (value) => {
* @param {object | null | undefined} node
* @returns {unknown}
*/
function converter(node) {
export function converter(node) {
// for negative number, ex) -10
if (isUnaryExpression(node)) {
const { operator, argument } = node;
Expand Down Expand Up @@ -134,7 +134,3 @@ function converter(node) {
//@ts-ignore
return node.value;
}

module.exports = {
converter,
};
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
const traverse = require("@babel/traverse").default;
const fs = require("fs");
const path = require("path");
const debug = require("debug")("ladle:vite");
const getAst = require("../get-ast.js");
import traverse from "@babel/traverse";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import debugFactory from "debug";
import getAst from "../get-ast.js";

const debug = debugFactory("ladle:vite");
const __dirname = path.dirname(fileURLToPath(import.meta.url));

/**
* @param {string} namedExport
Expand All @@ -12,7 +16,7 @@ const getAst = require("../get-ast.js");
const checkIfNamedExportExists = (namedExport, sourceCode, filename) => {
let exists = false;
const ast = getAst(sourceCode, filename);
traverse(/** @type {any} */ (ast), {
/** @type {any} */ (traverse).default(ast, {
/**
* @param {any} astPath
*/
Expand Down Expand Up @@ -55,7 +59,13 @@ const getComponents = (configFolder) => {
if (componentsExists || componentsExistsJs) {
if (checkIfNamedExportExists("Provider", sourceCode, filename)) {
debug(`Custom provider found.`);
return `import {Provider as CustomProvider} from '${relativePath}';\nexport const Provider = CustomProvider;\n`;
return `import {Provider as CustomProvider} from '${path.relative(
path.join(__dirname, "../../../app/src"),
path.join(
configFolder,
componentsExists ? "components.tsx" : "components.js",
),
)}';\nexport const Provider = CustomProvider;\n`;
}
debug("components.tsx exists");
debug(`Returning default no-op Provider.`);
Expand All @@ -65,4 +75,4 @@ const getComponents = (configFolder) => {
return noopProvider;
};

module.exports = getComponents;
export default getComponents;
15 changes: 10 additions & 5 deletions packages/ladle/lib/cli/vite-plugin/generate/get-config-import.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
const fs = require("fs");
const path = require("path");
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

/**
* @param {string} configFolder
*/
const getConfigImport = (configFolder) => {
const configPath = path.join(configFolder, "config.mjs");
const configExists = fs.existsSync(configPath);
const relativePath = "./config.js";
let configCode = `export let config = {};\n`;
if (configExists) {
configCode += `import customConfig from '${relativePath}';\nconfig = customConfig;\n`;
configCode += `import customConfig from '${path.relative(
path.join(__dirname, "../../../app/src"),
path.join(configFolder, "config.mjs"),
)}';\nconfig = customConfig;\n`;
}
return `${configCode}`;
};

module.exports = getConfigImport;
export default getConfigImport;
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const getStoryImports = require("./get-story-imports");
const getStoryList = require("./get-story-list");
const getConfigImport = require("./get-config-import");
const getComponentsImport = require("./get-components-import");
const getHmr = require("./get-hmr");
import getStoryImports from "./get-story-imports.js";
import getStoryList from "./get-story-list.js";
import getConfigImport from "./get-config-import.js";
import getComponentsImport from "./get-components-import.js";
import getHmr from "./get-hmr.js";

/**
* @param entryData {import('../../../shared/types').EntryData}
Expand All @@ -18,4 +18,4 @@ ${getHmr()}
`;
};

module.exports = getGeneratedList;
export default getGeneratedList;
2 changes: 1 addition & 1 deletion packages/ladle/lib/cli/vite-plugin/generate/get-hmr.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ const getHmr = () => `if (import.meta.hot) {
});
}`;

module.exports = getHmr;
export default getHmr;
18 changes: 14 additions & 4 deletions packages/ladle/lib/cli/vite-plugin/generate/get-meta-json.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { storyIdToMeta } = require("../naming-utils");
import { storyIdToMeta } from "../naming-utils.js";

/**
* @param entryData {import('../../../shared/types').EntryData}
Expand All @@ -20,15 +20,25 @@ const getMetaJson = (entryData) => {
homepage: "https://www.ladle.dev",
github: "https://github.com/tajo/ladle",
},
stories: /** @type {{[key: string]: {name: string; levels: string[]; parameters: any}}} */ ({}),
stories:
/** @type {{[key: string]: {name: string; levels: string[]; parameters: any}}} */ ({}),
};
storyIds.forEach((storyId) => {
result.stories[storyId] = {
...storyIdToMeta(storyId),
parameters: storyParams[storyId] ? storyParams[storyId].parameters : {},
};
});
return JSON.stringify(result, null, " ");
return result;
};

module.exports = getMetaJson;
/**
* @param entryData {import('../../../shared/types').EntryData}
*/
export const getMetaJsonString = (entryData) =>
JSON.stringify(getMetaJson(entryData), null, " ");

/**
* @param entryData {import('../../../shared/types').EntryData}
*/
export const getMetaJsonObject = (entryData) => getMetaJson(entryData);
Loading

0 comments on commit 94519c3

Please sign in to comment.