feat(admin): Improve DX for deploying admin externally (#3418)

* init deploy command

* add include flag

* add 'shortcut' flag

* add dev command, fix var replacement, change default behaviour

* cleanup params of build command

* fix defaults when using the plugin to serve admin

* add changeset

* fix globals

* update README

* throw error on no build found

---------

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>
This commit is contained in:
Kasper Fabricius Kristensen
2023-03-17 13:18:51 +01:00
committed by GitHub
parent 9ad15d3a88
commit 8a7421db5b
20 changed files with 358 additions and 85 deletions

View File

@@ -1,48 +1,100 @@
import { build as buildAdmin } from "@medusajs/admin-ui"
import { AdminBuildConfig, build as buildAdmin } from "@medusajs/admin-ui"
import dotenv from "dotenv"
import fse from "fs-extra"
import ora from "ora"
import { EOL } from "os"
import { resolve } from "path"
import { loadConfig, reporter, validatePath } from "../utils"
type BuildArgs = {
deployment?: boolean
outDir?: string
backend?: string
path?: string
include?: string[]
includeDist?: string
}
let ENV_FILE_NAME = ""
switch (process.env.NODE_ENV) {
case "production":
ENV_FILE_NAME = ".env.production"
break
case "staging":
ENV_FILE_NAME = ".env.staging"
break
case "test":
ENV_FILE_NAME = ".env.test"
break
case "development":
default:
ENV_FILE_NAME = ".env"
break
}
try {
dotenv.config({ path: process.cwd() + "/" + ENV_FILE_NAME })
} catch (e) {
reporter.warn(`Failed to load environment variables from ${ENV_FILE_NAME}`)
}
export default async function build(args: BuildArgs) {
const { path, backend, outDir } = mergeArgs(args)
const { deployment, outDir: outDirArg, backend, include, includeDist } = args
try {
validatePath(path)
} catch (err) {
reporter.panic(err)
let config: AdminBuildConfig = {}
if (deployment) {
config = {
build: {
outDir: outDirArg,
},
globals: {
backend: backend || process.env.MEDUSA_BACKEND_URL,
},
}
} else {
const { path, outDir } = loadConfig()
try {
validatePath(path)
} catch (err) {
reporter.panic(err)
}
config = {
build: {
outDir: outDir,
},
globals: {
base: path,
},
}
}
const time = Date.now()
const spinner = ora().start(`Building Admin UI${EOL}`)
await buildAdmin({
build: {
outDir: outDir,
},
globals: {
base: path,
backend: backend,
},
...config,
}).catch((err) => {
spinner.fail(`Failed to build Admin UI${EOL}`)
reporter.panic(err)
})
/**
* If we have specified files to include in the build, we copy them
* to the build directory.
*/
if (include && include.length > 0) {
const dist = outDirArg || resolve(process.cwd(), "build")
try {
for (const filePath of include) {
await fse.copy(filePath, resolve(dist, includeDist, filePath))
}
} catch (err) {
reporter.panic(err)
}
}
spinner.succeed(`Admin UI build - ${Date.now() - time}ms`)
}
const mergeArgs = (args: BuildArgs) => {
const { path, backend, outDir } = loadConfig()
return {
path: args.path || path,
backend: args.backend || backend,
outDir: args.outDir || outDir,
}
}

View File

@@ -1,15 +1,47 @@
import { Command } from "commander"
import build from "./build"
import dev from "./dev"
import eject from "./eject"
export async function createCli(): Promise<Command> {
const program = new Command()
const buildCommand = program.command("build")
buildCommand.description("Build the admin dashboard")
buildCommand.option(
"--deployment",
"Build for deploying to and external host (e.g. Vercel)"
)
buildCommand.option("-o, --out-dir <path>", "Output directory")
buildCommand.option("-b, --backend <url>", "Backend URL")
buildCommand.option("-p, --path <path>", "Base path")
buildCommand.option(
"-i, --include [paths...]]",
"Paths to files that should be included in the build"
)
buildCommand.option(
"-d, --include-dist <path>",
"Path to where the files specified in the include option should be placed. Relative to the root of the build directory."
)
buildCommand.action(build)
const devCommand = program.command("dev")
devCommand.description("Start the admin dashboard in development mode")
devCommand.option("-p, --port <port>", "Port (default: 7001))")
devCommand.option(
"-b, --backend <url>",
"Backend URL (default http://localhost:9000)"
)
devCommand.action(dev)
const deployCommand = program.command("eject")
deployCommand.description(
"Eject the admin dashboard source code to a custom directory"
)
deployCommand.option("-o, --out-dir <path>", "Output directory")
deployCommand.action(eject)
return program
}

View File

@@ -0,0 +1,6 @@
import type { AdminDevConfig } from "@medusajs/admin-ui"
import { dev as devAdmin } from "@medusajs/admin-ui"
export default async function dev(args: AdminDevConfig) {
await devAdmin(args)
}

View File

@@ -0,0 +1,111 @@
import * as fse from "fs-extra"
import path from "path"
import dedent from "ts-dedent"
type EjectParams = {
outDir?: string
}
const DEFAULT_DESTINATION = "medusa-admin-ui"
export default async function eject({
outDir = DEFAULT_DESTINATION,
}: EjectParams) {
const projectPath = require.resolve("@medusajs/admin-ui")
const uiPath = path.join(projectPath, "..", "..", "ui")
const packageJsonPath = path.join(projectPath, "..", "..", "package.json")
const pkg = await fse.readJSON(packageJsonPath)
const fieldsToRemove = ["exports", "types", "files", "main", "packageManager"]
fieldsToRemove.forEach((field) => delete pkg[field])
pkg.type = "module"
const dependenciesToMove = [
"tailwindcss",
"autoprefixer",
"postcss",
"tailwindcss-radix",
"@tailwindcss/forms",
"vite",
"@vitejs/plugin-react",
]
// Get dependencies in array from pkg.dependencies and move them to pkg.devDependencies
const dependencies = Object.keys(pkg.dependencies).filter((dep) =>
dependenciesToMove.includes(dep)
)
dependencies.forEach((dep) => {
pkg.devDependencies[dep] = pkg.dependencies[dep]
delete pkg.dependencies[dep]
})
pkg.scripts = {
build: "vite build",
dev: "vite --port 7001",
preview: "vite preview",
}
const viteConfig = dedent`
import { defineConfig } from "vite"
import dns from "dns"
import react from "@vitejs/plugin-react"
// Resolve localhost for Node v16 and older.
// @see https://vitejs.dev/config/server-options.html#server-host.
dns.setDefaultResultOrder("verbatim")
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
define: {
__BASE__: JSON.stringify("/"),
__MEDUSA_BACKEND_URL__: JSON.stringify("http://localhost:9000"),
},
})
`
// Create new tailwind.config.js file based on the current one
const tailwindConfig = await fse.readFile(
path.join(uiPath, "tailwind.config.js"),
"utf-8"
)
// Overwrite content field of module.exports in tailwind.config.js
let newTailwindConfig = tailwindConfig.replace(
/content:\s*\[[\s\S]*?\]/,
`content: ["src/**/*.{js,ts,jsx,tsx}", "./index.html"]`
)
// Remove require of "path" in tailwind.config.js
newTailwindConfig = newTailwindConfig.replace(
/const path = require\("path"\)/,
""
)
// Create a new postcss.config.js file
const postcssConfig = dedent`
module.exports = {
plugins: {
"tailwindcss/nesting": {},
tailwindcss: {},
autoprefixer: {},
}
}
`
const tmpPath = path.join(process.cwd(), outDir)
await fse.copy(uiPath, tmpPath)
await fse.remove(path.join(tmpPath, "tailwind.config.js"))
await fse.remove(path.join(tmpPath, "postcss.config.js"))
await fse.writeJSON(path.join(tmpPath, "package.json"), pkg)
await fse.writeFile(path.join(tmpPath, "vite.config.ts"), viteConfig)
await fse.writeFile(
path.join(tmpPath, "tailwind.config.cjs"),
newTailwindConfig
)
await fse.writeFile(path.join(tmpPath, "postcss.config.cjs"), postcssConfig)
}