Svelte | Svelte の開発環境用 Docker コンテナを作成する

Svelte の開発環境用 Docker コンテナを作成する。

ディレクトリー構成

1
2
3
4
+- docker-compose.yml
+- sveltejs
+- Dockerfile
+- package.json

docker-compose.yml

  • サブディレクトリー sveltejs に関連ファイルを配置する
  • 外部ポート(TCP:5000)と内部ポート(TCP:5000)をポートフォワード設定する
1
2
3
4
5
6
7
8
version: '2'
services:
svelte:
tty: true
build:
context: ./sveltejs
ports:
- "5000:5000"

sveltejs/Dockerfile

  • node イメージを使用する
  • helloworld プロジェクトを作成する
  • あらかじめ作成した package.json をコピーする
1
2
3
4
5
6
7
8
9
10
11
12
13
14
FROM  node:15.5.1-alpine3.12
WORKDIR /root
RUN apk upgrade && \
apk --no-cache add --update \
git\
&& npm install degit \
&& npx degit sveltejs/template helloworld

COPY ./package.json /root/helloworld/package.json
RUN cd helloworld \
&& npm install

WORKDIR /root/helloworld
CMD ["npm", "run", "dev"]

sveltejs/package.json

Docker コンテナの外部から Svelte サーバーに接続するには、–host オプションで 0.0.0.0 を指定する必要がある。

そこで、あらかじめ作成した package.json をコンテナ内にコピーする。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
"name": "svelte-app",
"version": "1.0.0",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public --host 0.0.0.0"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^16.0.0",
"@rollup/plugin-node-resolve": "^10.0.0",
"rollup": "^2.3.4",
"rollup-plugin-css-only": "^3.1.0",
"rollup-plugin-livereload": "^2.0.0",
"rollup-plugin-svelte": "^7.0.0",
"rollup-plugin-terser": "^7.0.0",
"svelte": "^3.0.0"
},
"dependencies": {
"sirv-cli": "^1.0.0"
}
}

パッケージ構成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
+ README.mdpackage-lock.json
+- node_modules
| +- ...
+- package.json
+- public
| +- build
| +- bundle.css
| +- bundle.js
| +- bundle.js.map
| +- favicon.png
| +- global.css
| +- index.html
| +- favicon.png
| +- global.css
| +- index.html
+- rollup.config.js
+- scripts
| +- setupTypeScript.js
+- src
+- App.svelte
+- main.js

src/App.svelte

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<script>
export let name;
</script>

<main>
<h1>Hello {name}!</h1>
<p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
</main>

<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}

h1 {
color: #ff3e00;
text-transform: uppercase;
font-size: 4em;
font-weight: 100;
}

@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>

src/main.js

1
2
3
4
5
6
7
8
import App from './App.svelte';

const app = new App({
target: document.body,
props: {
name: 'world'
}
});

実行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ curl http://localhost:5000/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>

<title>Svelte app</title>

<link rel='icon' type='image/png' href='/favicon.png'>
<link rel='stylesheet' href='/global.css'>
<link rel='stylesheet' href='/build/bundle.css'>

<script defer src='/build/bundle.js'></script>
</head>

<body>
</body>
</html>