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

fix: run frontend project in local .morph/frontend directory #19

Merged
merged 2 commits into from
Jan 16, 2025
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
112 changes: 49 additions & 63 deletions core/morph/api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,37 +22,10 @@
from morph.api.error import ApiBaseError, InternalError
from morph.api.handler import router

# TODO: clean build process & use mangum for lambda

# configuration values
build_required = os.getenv("MORPH_FRONT_BUILD", "false")
host = os.getenv("MORPH_UVICORN_HOST", "0.0.0.0")
port = os.getenv("MORPH_UVICORN_PORT", "9002")
server_url = f"http://{host}:{port}"
front_url = "http://localhost:3000"
token = "dummy"
environment = "development"
entrypoint_filename = "main.tsx"
template_dir = os.path.join(Path(__file__).resolve().parent, "templates", "development")

if build_required == "true":
environment = "production"
entrypoint_filename = "main-prod.tsx"
template_dir = os.path.join(
Path(__file__).resolve().parent, "templates", "production"
)
else:
init_index_template_path = os.path.join(
Path(__file__).resolve().parent, "templates", "index.html"
)
with open(init_index_template_path, "r") as f:
content = f.read()
content = content.replace("FRONT_URL", front_url)
index_template = os.path.join(template_dir, "index.html")
with open(index_template, "w") as f:
f.write(content)

templates = Jinja2Templates(directory=template_dir)
# set true to MORPH_LOCAL_DEV_MODE to use local frontend server
is_local_dev_mode = True if os.getenv("MORPH_LOCAL_DEV_MODE") == "true" else False

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="secret_key")
Expand All @@ -65,34 +38,52 @@
inertia_request_validation_exception_handler,
)

frontend_dir = os.path.join(Path(__file__).resolve().parents[1], "frontend")

manifest_json = os.path.join(frontend_dir, "dist", "manifest.json")
inertia_config = InertiaConfig(
templates=templates,
manifest_json_path=manifest_json,
environment=environment,
use_flash_messages=True,
use_flash_errors=True,
entrypoint_filename=entrypoint_filename,
assets_prefix="/src",
dev_url=front_url,
)
InertiaDep = Annotated[Inertia, Depends(inertia_dependency_factory(inertia_config))]
frontend_dir = os.path.join(os.getcwd(), ".morph", "frontend")


def get_inertia_config():
templates_dir = os.path.join(Path(__file__).resolve().parent, "templates")

if is_local_dev_mode:
frontend_url = "http://localhost:3000" # TODO: 被ったらずらす
templates = Jinja2Templates(directory=templates_dir)
templates.env.globals["local_dev_mode"] = True
templates.env.globals["frontend_url"] = frontend_url

return InertiaConfig(
templates=templates,
environment="development",
use_flash_messages=True,
use_flash_errors=True,
entrypoint_filename="main.tsx",
assets_prefix="/src",
dev_url=frontend_url,
)

return InertiaConfig(
templates=Jinja2Templates(directory=templates_dir),
manifest_json_path=os.path.join(frontend_dir, "dist", "manifest.json"),
environment="production",
entrypoint_filename="main.tsx",
)

frontend_dir = (
os.path.join(frontend_dir, "dist")
if inertia_config.environment != "development"
else os.path.join(frontend_dir, "src")
)

app.mount("/src", StaticFiles(directory=frontend_dir), name="src")
app.mount(
"/assets",
StaticFiles(directory=os.path.join(frontend_dir, "assets")),
name="assets",
)
inertia_config = get_inertia_config()

InertiaDep = Annotated[Inertia, Depends(inertia_dependency_factory(inertia_config))]

if is_local_dev_mode:
app.mount(
"/src",
StaticFiles(directory=os.path.join(frontend_dir, "src")),
name="src",
)
else:
app.mount(
"/assets",
StaticFiles(directory=os.path.join(frontend_dir, "dist", "assets")),
name="assets",
)

app.add_middleware(
CORSMiddleware,
Expand Down Expand Up @@ -137,8 +128,8 @@ async def index(inertia: InertiaDep) -> InertiaResponse:
return await inertia.render(
"index",
{
"baseUrl": server_url,
"token": token,
"baseUrl": "/",
"token": "dummy",
},
)

Expand All @@ -155,15 +146,10 @@ async def health_check():

@app.get("/{full_path:path}", response_model=None)
async def subpages(full_path: str, inertia: InertiaDep) -> InertiaResponse:
cwd = os.getcwd()
pages_dir = os.path.join(cwd, "src", "pages")
if not os.path.exists(os.path.join(pages_dir, f"{full_path}.mdx")):
return await inertia.render("404")

return await inertia.render(
full_path,
{
"baseUrl": server_url,
"token": token,
"baseUrl": "/",
"token": "dummy",
},
)
Empty file.
10 changes: 8 additions & 2 deletions core/morph/api/templates/index.html
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
<!DOCTYPE html>
<html>
<head>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
{% inertia_head %}

<!-- For Vite -->

{% if local_dev_mode and frontend_url %}
<script type="module">
import RefreshRuntime from "FRONT_URL/@react-refresh";
import RefreshRuntime from "{{ frontend_url }}/@react-refresh";
RefreshRuntime.injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;
window.__vite_plugin_react_preamble_installed__ = true;
</script>
{% endif %}

<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
Expand Down
12 changes: 0 additions & 12 deletions core/morph/api/templates/production/index.html

This file was deleted.

1 change: 1 addition & 0 deletions core/morph/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ def sync(
@params.stop
@params.build
@params.no_log
@params.preview
@click.pass_context
@global_flags
@requires.preflight
Expand Down
6 changes: 6 additions & 0 deletions core/morph/cli/params.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,3 +251,9 @@ def convert_value(val: str) -> Any:
type=str,
help="Specify the project id.",
)

preview = click.option(
"--preview",
is_flag=True,
help="Serve application with pre-built frontend assets locally to simulate a production environment for testing.",
)
30 changes: 0 additions & 30 deletions core/morph/frontend/README.md

This file was deleted.

1 change: 0 additions & 1 deletion core/morph/frontend/constants-base.js

This file was deleted.

1 change: 0 additions & 1 deletion core/morph/frontend/constants.d.ts

This file was deleted.

Loading
Loading