Tailwind 2가 포함된 Sveltekit Vite

postcss 및 tailwind를 사용하는 svelte@next

업데이트 :



5. SvelteKit Vite로 업데이트하면 모두 작동합니다. 이 게시물은 오래되어 더 이상 유지되지 않습니다. 저장소를 확인하세요.
4. 데모 추가
3.makerun build 정적build/ 디렉토리 내보내기
2.수정run build 오류
1. 엄청난 오류 수정

멈추다



Pump the brakes! A little disclaimer...

svelte@next is not ready for use yet. It definitely can't
run your apps, and it might not run at all.

We haven't yet started accepting community contributions,
and we don't need people to start raising issues yet.

Given these warnings, please feel free to experiment, but
you're on your own for now. We'll have something to show
soon.

Sapper v1은 출시되지 않고 대신 Svelte가 추가로 개발되고 있습니다. 자세한 내용은 dev.to의 jessenkinner 게시물을 확인하세요.

그러나 그것은 내가 진심으로 시도하는 것을 막지 못했습니다.

그나저나 pnpm을 이제야 알게 되었고 알고 사용하게 되어 매우 기뻤습니다. 따라서 pnpm 또는 npm 대신 yarn 를 사용하겠습니다. 둘 다 같은 용도로 사용됩니다.

Svelte 프로젝트 생성



지금은 pnpm가 설치되어 있다고 가정하고 터미널에서 이 명령을 실행할 수 있습니다.

pnpm init svelte@next svelte-next
cd svelte-next
pnpm i


여기서 svelte-next는 프로젝트 디렉토리의 이름입니다. typescript를 사용할지 여부를 선택할 수 있습니다.

더 진행하기 전에 아래 명령을 실행하고 브라우저에서 localhost:3000에 액세스하여 현재 버전이 개발하기에 "정상"인지 확인할 수 있습니다.

pnpm run dev


이런 에러가 났다면

Error: NOT_FOUND
    at Object.loadUrl (C:\Users\hp\www\sveltest\node_modules\.pnpm\[email protected]\node_modules\snowpack\src\commands\dev.ts:607:13)
    at C:\Users\hp\www\sveltest\node_modules\.pnpm\@sveltejs\[email protected]\node_modules\@sveltejs\kit\src\api\dev\index.js:167:14


snowpack 구성에 문제가 있는 것 같으니 plugins 줄을 다음과 같이 편집하십시오.

    plugins: [
        [
            "@snowpack/plugin-svelte",
            {
                compilerOptions: {
                    hydratable: true
                }
            }
        ],
        '@snowpack/plugin-typescript'
    ],


dev 서버를 중지하고 다시 실행하십시오.

전처리 설정



typescript를 사용하지 않는 경우 이 명령을 실행하여 전처리를 수동으로 추가해야 합니다.

pnpm i -D svelte-preprocess


그런 다음 svelte에 전처리를 적용하여 PostCSS를 추가합니다.

// svelte.config.js
const sveltePreprocess = require('svelte-preprocess');
module.exports = {
    // Consult https://github.com/sveltejs/svelte-preprocess
    // for more information about preprocessors
    preprocess: [
        sveltePreprocess({
            defaults: {
                script: 'typescript',
                style: 'postcss',
            },
            postcss: true
        }),
    ],
    kit: {
        // By default, `npm run build` will create a standard Node app.
        // You can create optimized builds for different platforms by
        // specifying a different adapter
        adapter: '@sveltejs/adapter-node',

        // hydrate the <div id="svelte"> element in src/app.html
        target: '#svelte'
    }
};


구성 요소의 기본 언어를 정의하는 객체 속성default입니다. 따라서 위의 구성은 TypeScript를 기본 언어로 만들어 스크립트 태그에 lang="ts"를 추가하고 스타일 태그에 lang="postcss"를 추가할 필요가 없습니다.

PostCSS 및 Tailwind 추가




pnpm add -D @snowpack/plugin-postcss postcss postcss-cli postcss-load-config postcss-preset-env
pnpm add -D tailwindcss autoprefixer cssnano


svelte@next는 아직 개발 중이므로 프로덕션으로 가져오지 않을 수도 있으므로 필요하지 않은 경우 autoprefixer 또는 cssnano를 건너뛸 수 있습니다.

중첩에 postcss-preset-env를 사용합니다. postcss-nesting와 같은 다른 플러그인을 사용할 수 있습니다.

PostCSS 설정



Snowpack 구성 파일 편집

// snowpack.config.js
// Consult https://www.snowpack.dev to learn about these options
module.exports = {
    extends: '@sveltejs/snowpack-config',
    plugins: [
        [
            '@snowpack/plugin-build-script',
            {
                cmd: "postcss",
                input: [".css", ".pcss"],
                output: [".css"],
            }
        ],
        [
            "@snowpack/plugin-svelte",
            {
                compilerOptions: {
                    hydratable: true
                }
            }
        ],
        '@snowpack/plugin-typescript'
    ],
    mount: {
        'src/components': '/_components'
    },
    alias: {
        $components: './src/components'
    }
};



프로젝트의 루트 폴더에 PostCSS 구성 파일을 만듭니다. 이런 식으로.

// postcss.config.js
const mode = process.env.NODE_ENV;
const dev = mode === "development";

module.exports = {
    plugins: [
        require('postcss-preset-env')({stage: 1}),
        require("tailwindcss"),
        require("autoprefixer"),

        !dev && require("cssnano")({
            preset: "default",
        }),
    ],
};


Tailwind 설정



이 명령을 실행

npx tailwind init


Tailwind 구성 수정

// taiwind.config.js
const { tailwindExtractor } = require("tailwindcss/lib/lib/purgeUnusedStyles");

module.exports = {
    purge: {
        content: [
            "./src/**/*.html",
            "./src/**/*.svelte"
        ],
        options: {
            defaultExtractor: (content) => [
                ...tailwindExtractor(content),
                ...[...content.matchAll(/(?:class:)*([\w\d-/:%.]+)/gm)].map(([_match, group, ..._rest]) => group),
            ],
            keyframes: true,
        },
    },
    darkMode: 'class',
    theme: {
        extend: {},
    },
    variants: {
        extend: {},
    },
    plugins: [],
};


tailwindExtractor는 향후 사용을 위한 것이므로 class: 지시문을 사용할 수 있습니다.

테일윈드 사용 준비 완료



만들기src\routes\global.pcss
@tailwind base;
@tailwind components;
@tailwind utilities;



그런 다음 사용src\routes\$layout.svelte
<script>
    import './global.pcss';
</script>

<slot/>


src\routes\index.svelte
<script>
    import Counter from '$components/Counter.svelte';
</script>

<main>
    <h1 class="uppercase text-5xl font-extrabold my-16">Hello world!</h1>

    <Counter/>
    <p>Visit the <a href="https://svelte.dev">svelte.dev</a> to learn how to build Svelte apps.</p>
</main>

<style>
  main {
    @apply px-8 py-16 mx-auto max-w-5xl text-center;
  }

  * + * {
    @apply mb-0 mt-4;
  }

  p {
    @apply text-xl;
  }
</style>


상용구





다크 모드 토글 테마로 만든 상용구를 사용해보고 싶다면 내 저장소here를 확인할 수 있습니다.

업데이트 :


  • netlify에서 배포할 수 있는 정적 사이트를 생성하려면 빌드 명령을 실행하면 됩니다. 이미 저장소를 업데이트합니다
  • .
  • Live Demo

  • 아직도 영어로 글을 쓰는 법을 배우고 있습니다. 명심하시기 바랍니다.

    다른 오류를 발견하면 댓글

    감사해요

    좋은 웹페이지 즐겨찾기