これをするとどうなる?
SvelteでTypeScriptを書くとき、通常は<script lang="ts">とlang設定を書きますが、これを<script>でもTypeScriptと認識させることができます![]()
以下はVSCodeでlangのデフォルト設定をしていない時と、した時の比較です。
|
|
|
|---|---|
![]() |
![]() |
メリット
- コーディング時に
langを書かなくていいから楽
- スッキリするので可読性が上がる
-
<style>にシンタックスハイライトがされて読みやすい
-
設定方法
1. svelte.config.jsファイルを作成
svelte.config.jsファイルを作成してください。保存場所はrollup.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設定を読み込ませます。
// ...
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を実行します。

これで、先程まで出ていた警告が消えました![]()

ビルドも正常に動きブラウザに表示されました。

まとめ
2020年の初期だったでしょうか、SvelteがTypeScriptに対応するにはどうしたら良いか議論がされていました。そこで、Vueで使われているVeturというVue Language Serverにヒントを得て、同様の仕組みをSvelteも採用することになりました。
詳しくありませんが、どうやらLanguage Serverは言語解析をしてくれてVScodeに合ってるよ/間違ってるよを教えてくれるもののようです。(間違っていたらご指摘ください
)
このおかげで、SvelteでもTypeScriptをVSCodeで書けるようになりました。
先日、『State of JavaScript 2020』でReactを抜き満足度・興味で首位になったSvelte。今後も使う人が増えるといいですね。
参考サイト
- Using Preprocessors
- Svelte <3 TypeScript

