Svelte配置TailwindUI后无法启动,报import和@tailwind解析错误
问题原因&解决方案
第一个报错:postcss.config.js 无法使用import语句
导致原因有3个:
- 你将配置文件错误命名为了
postcss.config.css,Node不会将css后缀文件识别为JS配置文件 - 配置文件中没有引入
tailwindcss模块就直接调用了tailwind()方法 - 配置末尾存在多余的
};语法错误,同时如果你的项目没有在package.json中声明"type": "module",Node默认使用CommonJS规范,不支持ES模块的import/export语法
第二个报错:Svelte无法识别@字符
你将Tailwind的CSS指令@tailwind错误写在了<script>标签中,这类指令属于CSS语法,需要放在<style>标签内,且需要postcss正常生效后才会被正确解析,在postcss配置异常的情况下,Svelte会将<script>内的内容全部作为JS语法解析,自然会把@识别为非法字符。
完整修复步骤
- 重命名配置文件:将
postcss.config.css修改为postcss.config.js - 修正postcss配置内容,根据你的项目模块规范二选一:
方案A:项目使用ES模块规范(package.json有"type": "module")
import tailwind from 'tailwindcss' import autoprefixer from 'autoprefixer' import nesting from 'postcss-nesting' export default { syntax: 'postcss-scss', plugins: [ nesting(), tailwind(), autoprefixer(), ], }
方案B:项目使用CommonJS规范
const tailwind = require('tailwindcss') const autoprefixer = require('autoprefixer') const nesting = require('postcss-nesting') module.exports = { syntax: 'postcss-scss', plugins: [ nesting(), tailwind(), autoprefixer(), ], }
- 修改
src/App.svelte代码,将@tailwind指令移到<style>标签内:
<script> // 原有JS逻辑保留在这里 </script> <style> @tailwind base; @tailwind components; @tailwind utilities; /* 其他自定义样式写在这里 */ </style>
内容的提问来源于stack exchange,提问作者rubyist
相关产品推荐
相关产品推荐

