LoginSignup
1

More than 3 years have passed since last update.

svelteファイルのscript | style タグにデフォルト lang を設定する方法

Last updated at Posted at 2021-01-15

これをするとどうなる?

SvelteTypeScriptを書くとき、通常は<script lang="ts">lang設定を書きますが、これを<script>でもTypeScriptと認識させることができます:yum:

以下はVSCodelangのデフォルト設定をしていない時と、した時の比較です。

:thumbsdown: デフォルト設定なし :thumbsup: デフォルト設定あり
image.png image.png

メリット

  • コーディング時にlangを書かなくていいから楽 :rocket:
  • スッキリするので可読性が上がる :dizzy:
    • <style>にシンタックスハイライトがされて読みやすい

設定方法

1. svelte.config.jsファイルを作成

svelte.config.jsファイルを作成してください。保存場所はrollup.config.jsと同じ階層です。

svelte.config.js
const sveltePreprocess = require('svelte-preprocess');

function createPreprocessors(production) {
  return sveltePreprocess({
    // ここでscriptやstyleタグのデフォルトlangを指定します
    defaults: {
      script: 'typescript',
      style: 'postcss',
    },
    // その他の設定
    postcss: {
      plugins: [
        require('tailwindcss'),
        require('postcss-import'),
        ...(production
          ? [
              require('autoprefixer'),
              require('cssnano')({ preset: 'default' }),
            ]
          : []),
      ],
    }
  });
};

module.exports = {
  preprocess: createPreprocessors(true),
  createPreprocessors,
};

2. rollup.config.jsの設定

rollup.config.jsに、先ほどsvelte.config.jsで設定したpreprocess設定を読み込ませます。

rollup.config.js
// ...
const createPreprocessors = require('./svelte.config').createPreprocessors;
const production = !process.env.ROLLUP_WATCH;

export default {
    // ...
    plugins: [
        // ...
        svelte({
            // ...
            preprocess: createPreprocessors(production),
        }),
        // ...
    ],
};
// ...

3. Svelte Language Serverの再起動

これらの設定をしたらSvelte Language Serverを再起動します。
VSCodeでcmd-shift-pでコマンドパレットを開き、svelte restartと入力したら、候補に出てくるSvelte: Restart Language Serverを実行します。
image.png
これで、先程まで出ていた警告が消えました:sparkles:
image.png
ビルドも正常に動きブラウザに表示されました。
image.png

まとめ

2020年の初期だったでしょうか、SvelteTypeScriptに対応するにはどうしたら良いか議論がされていました。そこで、Vueで使われているVeturというVue Language Serverにヒントを得て、同様の仕組みをSvelteも採用することになりました。
詳しくありませんが、どうやらLanguage Serverは言語解析をしてくれてVScodeに合ってるよ/間違ってるよを教えてくれるもののようです。(間違っていたらご指摘ください :bow:
このおかげで、SvelteでもTypeScriptVSCodeで書けるようになりました。

先日、『State of JavaScript 2020』Reactを抜き満足度・興味で首位になったSvelte。今後も使う人が増えるといいですね。

参考サイト

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
1