はなゐろぐ

主に技術関係の覚え書きです。

Sapper(Svelte)でSassとTailwind CSSを使う

2020年12月25日

導入

インストール

$ npx degit "sveltejs/sapper-template#rollup" sapper
$ cd sapper
$ npm install
$ npm i -D tailwindcss svelte-preprocess sass postcss autoprefixer
$ npx tailwind init

IE11をサポートするなら、tailwindcss@1.9.6を入れます。

Tailwind CSS の設定

tailwind.config.js
module.exports = {
  purge: {
    content: ['./src/**/*.svelte', './src/**/*.html'],
  },
};

未使用クラスを削除するPurgeCSSの設定を記入します。デフォルトではproductionの時のみ走る処理です。強制的にproductionにするなら、コマンドの頭にNODE_ENV=productionをつけます。

バンドラ(Rollup)の設定

rollup.config.js
import sveltePreprocess from 'svelte-preprocess';

const preprocess = {
  ...sveltePreprocess({
    sourceMap: dev,
    scss: true,
    postcss: {
      plugins: [
        require('tailwindcss'),
        require('autoprefixer')({ grid: 'no-autoplace' }),
      ],
    },
  }),
};

export default {
  client: {
    plugins: [
      svelte({
        dev,
        hydratable: true,,
        preprocess, // <- 追加 clientとserver両方
        emitCss: true
      }),
    ],
  },
};

CSSの処理設定を追記。途中ちょこちょこ端折ってますが…。

Svelte で Tailwind CSS を読み込む

_layout.svelte
<style global>
  @tailwind base;
  @tailwind components;
  @tailwind utilities;
</style>

Lint 系設定

Stylelint

Svelte、Tailwind CSSの独自記法を許容させる。Prettierも入れます。

.stylelintrc.js
module.exports = {
  extends: [
    'stylelint-config-standard',
    'stylelint-config-prettier',
  ],
  rules: {
    'at-rule-no-unknown': [
      true,
      {
        ignoreAtRules: [
          // Tailwind CSS
          'tailwind',
          'apply',
          'variants',
          'responsive',
          'screen',
        ],
      },
    ],
  },
};

ESLint

Svelteプラグインを入れます。Prettierも入れます。ESLintには<style>を無視してほしいので、その設定も追記。

.eslintrc.js
module.exports = {
  parserOptions: {
    ecmaVersion: 2019,
    sourceType: 'module',
  },
  env: {
    es6: true,
    browser: true,
  },
  extends: ['eslint-config-standard', 'prettier'],
  plugins: ['svelte3'],
  overrides: [
    {
      files: ['*.svelte'],
      processor: 'svelte3/svelte3',
    },
  ],
  settings: {
    'svelte3/ignore-styles': () => true,
  },
};

Prettier

Tailwind CSSを使うとどうしてもclass属性が長くなりがちなので、*.svelteの折返し幅を少しゆるめます。この値は各自お好みで。

.prettierrc.js
module.exports = {
  overrides: [
    {
      files: '*.svelte',
      options: {
        printWidth: 120,
      },
    },
  ],
};

prettier-plugin-tailwindも使いたいのですが、これを書いてる時点でSvelteをサポートしていないのでとりあえず見送り。Issueには要望が上がっているので期待したいですが、コミット履歴を見るに以前サポートしていたのをとりやめたようなので、難しいのかも…。