LoginSignup
7
5

More than 3 years have passed since last update.

人気急上昇中のwebフレームワーク「Svelte」の紹介 #実践編

Last updated at Posted at 2020-12-07

初めに

本記事は2020年木更津高専アドベントカレンダー の8日目の投稿です。
また素人記事なため温かい目で見守ってください。
昨日の紹介記事はこちら

只今の時刻は0:25。記事当日です。急ぎます><

環境構築

とりあえずhello worldしましょう!!!

$ npm -g install yarn
$ yarn global degit
$ degit sveltejs/template svelte-project

これでテンプレートを落とします

とりあえずディレクトリに入って中を見てみましょう


$ cd .\ svelte-project\
$ ls

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2020/12/08      0:46                public
d-----       2020/11/24     18:58                scripts
d-----       2020/12/08      0:46                src
-a----       2020/11/24     18:58             41 .gitignore
-a----       2020/11/24     18:58            520 package.json
-a----       2020/11/24     18:58           2903 README.md
-a----       2020/11/24     18:58           1841 rollup.config.js

まだnode_modulesがないので落としてきます

$ yarn

success Saved lockfile.
Done in hoge s.

こう出たら成功です。
再びlsしてみると


$ ls

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2020/12/08      0:55                node_modules
d-----       2020/12/08      0:46                public
d-----       2020/11/24     18:58                scripts
d-----       2020/12/08      0:46                src
-a----       2020/11/24     18:58             41 .gitignore
-a----       2020/11/24     18:58            520 package.json
-a----       2020/11/24     18:58           2903 README.md
-a----       2020/11/24     18:58           1841 rollup.config.js
-a----       2020/12/08      0:55          29676 yarn.lock

これで基本的には完了です。

一旦起動してみましょうか

$ yarn run dev
rollup -c -w
rollup v2.34.2
bundles src/main.js → public\build\bundle.js...
LiveReload enabled
created public\build\bundle.js in 277ms

[2020-12-08 01:04:56] waiting for changes...

> svelte-app@1.0.0 start
> sirv public "--dev"

  Your application is ready~! 🚀

  - Local:      http://localhost:5000
  - Network:    Add `--host` to expose

────────────────── LOGS ──────────────────

こんな感じになったら成功です早速http://localhost:5000 にアクセスしてみましょう

image.png

公式のhello worldが出てくるはずです~

コードを変更してみましょうか。
run dev を起動したままでいいので、srcのApp.svelteを編集します。

なにか書いてあると思うので、一回全て消してこうしてください

hello world

???
と思った方もいるでしょう。もっとプログラミングぽいなにかとか、俗に言うおまじないとか書かなくていいのって。
僕もはじめは思いました。
Hello Worldくらいならこの記述量で可能です❗❗

再びhttp://localhost:5000 を見てみると
image.png
こうなっています!
コレであなたもフロントエンドエンジニア💻

TypeScript対応

このままではJavaScriptしか書けません!!!!
大変!!

対応させましょう!

$ yarn add -D svelte-preprocess @rollup/plugin-typescript typescript svelte-check

これで必要なパッケージ周りをインストールします

次にコンフィグ周り、いじってきます。

まずrollup.config.js

import svelte from 'rollup-plugin-svelte';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import css from 'rollup-plugin-css-only';

import typescript from "@rollup/plugin-typescript";
import sveltePreprocess from "svelte-preprocess";

const production = !process.env.ROLLUP_WATCH;

function serve() {
    let server;

    function toExit() {
        if (server) server.kill(0);
    }

    return {
        writeBundle() {
            if (server) return;
            server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
                stdio: ['ignore', 'inherit', 'inherit'],
                shell: true
            });

            process.on('SIGTERM', toExit);
            process.on('exit', toExit);
        }
    };
}

function typeCheck() {
  return {
    writeBundle() {
      require('child_process').spawn('svelte-check', {
        stdio: ['ignore', 'inherit', 'inherit'],
        shell: true
      });
    }
  }
}

export default {
    input: 'src/main.ts',
    output: {
        sourcemap: true,
        format: 'iife',
        name: 'app',
        file: 'public/build/bundle.js'
    },
    plugins: [
        typeCheck(),
        typescript({ sourceMap: !production }),
        svelte({
            preprocess: sveltePreprocess(),
            compilerOptions: {
                dev: !production
            }
        }),
        // we'll extract any component CSS out into
        // a separate file - better for performance
        css({ output: 'bundle.css' }),

        // If you have external dependencies installed from
        // npm, you'll most likely need these plugins. In
        // some cases you'll need additional configuration -
        // consult the documentation for details:
        // https://github.com/rollup/plugins/tree/master/packages/commonjs
        resolve({
            browser: true,
            dedupe: ['svelte']
        }),
        commonjs(),

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        !production && serve(),

        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        !production && livereload('public'),

        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production && terser()



    ],
    watch: {
        clearScreen: false
    }
};

つぎにtsconfig.jsonを作ります。
ここは割と宗教的なとこがあるので各自自由に作ってください。

とりあえず最低限書いたのをおいておきます

{
  "include": ["src/**/*"],
  "exclude": ["node_modules/*", "public/*"],
  "compilerOptions": {
    "target": "ESNEXT",
    "lib": ["ESNEXT", "dom"],
    "module": "ESNEXT",
    "moduleResolution": "node",

    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,

    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "strictNullChecks": true
  }
}

最後にsrc/main.jsの名前をsrc/main.tsに変えて

$ yarn start

起動❗
おそらく起動できていると思います。

tsの書き方は


<script lang = "ts">
    let a: number = 1;
    let b: number = 2;
</script>

<input type="number" bind:value={a}>
<input type="number" bind:value={b}>

<p>{a} + {b} = {a + b}</p>

このようにscript のところにlang = "ts"を書くことでできます。

これで基本コーディングは初めれると思います!

最後に

自分はSvelteはReact使うにはすこし敷居が高いときなどにぱぱっと書いたりするときに使っています!
みなさんもぜひ使ってみてください!

7
5
1

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
7
5