0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Azure Static Web Appsでサブディレクトリを切ってみたメモ

Last updated at Posted at 2025-06-19

概要

Azure Static Web Appsで2つのアプリをサブディレクトリを切って共存させた。
AWSのCloudfrontのように、後からS3にファイルを置くような形はとれないが、
同時にデプロイして、デプロイ先のフォルダを共有することで実現できることを確認した。

https://gentle-smoke-0024c9c00.5.azurestaticapps.net/sub/
https://gentle-smoke-0024c9c00.5.azurestaticapps.net/app/

この時点のソース

ディレクトリ構造

+ app
- apps
  + vite-project
- public
  - index.html
- dist
  - index.html
  - staticwebapp.config.json
  + app
  + sub

サブディレクトリ用の設定のポイント

ルーティング設定はサブディレクトリごとに行う

staticwebapp.config.json
{
  "routes": [
    { "route": "/app/assets/*" },
    {
      "route": "/app/*",
      "rewrite": "/app/index.html"
    },
    { "route": "/sub/assets/*" },
    {
      "route": "/sub/*",
      "rewrite": "/sub/index.html"
    }
  ]
}

vite.config.tsでベースパスを/sub/、ビルド先を./distに設定する

apps/vite-project
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
+  base: '/sub/',
  plugins: [react()],
  build: {
+    outDir: '../../dist/sub',
  },
});

React Routerでベースパスを設定する

apps/vite-project/src/App.tsx
import { useState } from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import reactLogo from './assets/react.svg';
import viteLogo from '/sub/vite.svg';
import './App.css';
import Page2 from './Page2';

function Home() {

  return (
    <>
      <h1>Vite + React</h1>
      <nav style={{ marginTop: '20px' }}>
        <Link
          to="/page2"
          style={{ color: '#646cff', textDecoration: 'underline' }}
        >
          Go to Page2
        </Link>
      </nav>
    </>
  );
}

function App() {
  return (
+    <Router basename="/sub">
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/page2" element={<Page2 />} />
      </Routes>
    </Router>
  );
}

export default App;

余談: エラーが出ずにデプロイに失敗してハマった

$ swa deploy ./dist --env production
Deploying project to Azure Static Web Apps...

エラーも出さずにここで止まってしまう。

原因は、./dist/index.htmlを入れ忘れたことだった。
せめて、ルートフォルダにindex.htmlは必須ですとか、なにか言ってほしい

参考

Azure Static Web Apps をパイプラインを使わずSWA CLIでデプロイしたメモ
Bicepを使ってAzure Static Web Appsのリソースをデプロイしたメモ
作成済のAzure Static Web Apps に Azure DevOps からデプロイしたメモ
AWS CDKで既存のCloudFrontにデプロイしたメモ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?