ぼくの考えるさいきょうのSvelte開発環境

2024年4月現時点でのSvelte開発環境をボイラープレートにしようと思いまして。 手順書も兼ねているので長文になる予定です。 成果物はこちら↓ https://github.com/dev-komenzar/riceplate

仕様

Bun + SvelteKit のセットアップ

:::details 次のステップもまとめて構築するコマンド コミュニティによるユーティリティsvelte-addを利用して次セクションまで自動でインストールできます。

npm create @svelte-add/kit@latest my-svelte-boilerplate -- --package-manager=bun --with typescript+postcss+postcss-autoprefixer+tailwindcss+tailwindcss-forms+tailwindcss-typography

途中にある--はタイポじゃなく必要です。 Link: svelte-add/svelte-add: Easily add integrations and other functionality to Svelte apps

ちなみにこのコマンドをnpmでなくbunで実行すると途中で止まりました。バグっぽいです。 :::

アプリ名はmy-svelte-boilerplateとします。

bun create svelte@latest my-svelte-boilerplate

:::details Outputs

create-svelte version 6.0.10

┌  Welcome to SvelteKit!
│
◇  Which Svelte app template?
│  Skeleton project
│
◇  Add type checking with TypeScript?
│  Yes, using TypeScript syntax
│
◇  Select additional options (use arrow keys/space bar)
│  Add ESLint for code linting
│
└  Your project is ready!

✔ Typescript
  Inside Svelte components, use <script lang="ts">

Install community-maintained integrations:
  https://github.com/svelte-add/svelte-add

Next steps:
  1: cd my-svelte-boilerplate
  2: bun install
  3: git init && git add -A && git commit -m "Initial commit" (optional)
  4: bun run dev -- --open

To close the dev server, hit Ctrl-C

Stuck? Visit us at https://svelte.dev/chat

:::

参考

Autoprefixer, Tailwindを自動インストール

一部のパッケージはsvelte-addを利用すると簡単にインストールできます。bunx svelte-addでautoprefixer, tailwind, eslintをインストールしていきます。

$ bunx svelte-add@latest postcss --postcss-autoprefixer

PostCSS
 ✅ already set up! skipping.
Create or find an existing issue at https://github.com/svelte-add/svelte-add/issues if this is wrong.

Run bun install to install new dependencies, and then reload your IDE before starting your app.
$ bunx svelte-add@latest tailwindcss

PostCSS
 ✅ successfully set up and repaired (it looks like it was in a broken setup before this command was run)!
Create or find an existing issue at https://github.com/svelte-add/svelte-add/issues if this is wrong.

Tailwind CSS
 ✅ successfully set up and repaired (it looks like it was in a broken setup before this command was run)!
Create or find an existing issue at https://github.com/svelte-add/svelte-add/issues if this is wrong.

bun installを実行すると新しい依存パッケージがインストールされます。

ESLint Config

最近はantfu/eslint-configがお気に入りなので、eslintとこのコンフィグも入れます。次のコマンドでダイアログが出てきます。

bunx @antfu/eslint-config@latest

ダイアログにて使用フレームワークを選ぶのでsvelteを選択。Flat configのeslint.config.jsが作られるので、.eslintignore, .eslintrc.cjsは手動で削除します。そしてbun installで依存関係をインストール。

その後eslint.config.jsは好きにカスタムしましょう!

:::details 私のeslint.config.js

こだわりは'style/key-spacing'です!

import antfu from '@antfu/eslint-config'

export default antfu(
 {
  stylistic: {
   indent: 'tab',
   quotes: 'single',
  },
  typescript: true,
  svelte:     true,
        ignores:   [...],
 },
 {
  files: ['*.svelte'],
  rules: {
   'svelte/indent': [
    'error',
    { indent: 'tab', alignAttributesVertically: true },
   ],
   'svelte/block-lang': [
    'error',
    {
     enforceScriptPresent: true,
     enforceStylePresent:  false,
     script:               ['ts'],
     style:                ['scss', null],
    },
   ],
   'svelte/html-self-closing': [
    'error',
    'all',
   ],
   'svelte/sort-attributes': 'error',
  },
 },
 {
  rules: {
   'style/key-spacing': [
    'error',
    {
     align: 'value',
    },
   ],
   'style/no-multi-spaces': [
    'error',
    {
     exceptions: {
      ArrayExpression:  true,
      TSTypeAnnotation: true,
     },
    },
   ],
   'style/type-annotation-spacing': [
    'error',
    { before: false, after: true },

   ],
   'prefer-const': 'off',
  },
 },

)

:::

一度 bun run eslint --fix .を走らせておきましょう。

Stylelint

stylelintとルールを追加します。

bun add -D stylelint stylelint-config-standard stylelint-config-html stylelint-config-recess-order stylelint-declaration-block-no-ignored-properties

.stylelintrc.yamlを作成します。

:::details 私のコンフィグ

extends:
  - stylelint-config-html
  - stylelint-config-recess-order
  - stylelint-declaration-block-no-ignored-properties

:::

Husky + staged

https://zenn.dev/articles/c549f5203f8bba/edit

以前にまとめた記事を参考にしました。今回チェックするとhuskyのドキュメントにbunの記述が追加されていましたね。

MSW

https://zenn.dev/kometan/articles/7ff9bd60c94147

モックで使用するMSWもインストールしておきます。こちらも以前に記事にしたものを参考にしました。改めて読むと筋が通っていないところがあるので修正しないとな。

今回は

  1. bun add --dev msw @iodigital/vite-plugin-mswをパッケージをインストール
  2. src/mockに3つのファイル作成:handlers.ts, browsers.ts, servers.ts
  3. フックを設定 src/以下にhooks.client.ts, hooks.server.ts
  4. vite.config.tsのプラグインにvite-plugin-mswを追加

エディターの準備

VS Codeをbunで便利に使えるようにカスタムします。まず設定を書きます。.vscode/setting.jsonを作成し、

{
 "npm.packageManager": "bun"
}

値は"bun"あるいは"auto"で。 これで、サイドバーのNPM SCRIPTSからタスクを実行する時にbunが使えます。

なお、ユーザー設定で "npm.packageManager": "auto"以外ではうまく動作しませんでした。自分の環境では最初"yarn"になっており苦戦しました。ユーザー設定の方が優先されるのか?

また、dev serverを起動するコマンドbun run devはデフォルトでNodeを使用します。bunを使用するにはbun --bun run devとbunフラグを追加する必要があります。これを実行しやすいように.vscode/tasks.jsonを書きます。

{
 "version": "2.0.0",
 "tasks": [
  {
   "type": "shell",
   "command": "bun",
   "args": [
    "--bun",
    "run",
    "dev"
   ],
   "label": "bun: dev",
   "detail": "bun run dev using bun runtime",
   "group": "test",
   "problemMatcher": [],
   "presentation": {
    "echo": true,
    "reveal": "always",
    "focus": false,
    "panel": "shared",
    "showReuseMessage": true,
    "clear": false
   }
  }
 ]
}

まとめ

https://github.com/dev-komenzar/riceplate

以上でテンプレができました。このリポジトリをクローンしてbun installすると使えます。

ここまで長々と書いてきました。これで今後プロジェクトを始めるとき楽になると思います。依存先のアップデートや自分の考えが変わればアップデートしていこうと思います。

ライセンスはMITにしているので、ご自由に使ってみてください。改善点があればコメントやGithubなどでお待ちしています。