在全新Next.js项目中安装Tailwind CSS后运行npm run dev报错
错误信息
error - ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet1.rules[3].oneOf[11].use1!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet1.rules[3].oneOf[11].use[2]!./styles/globals.css
/Users/andregomes/Desktop/Note/todo/tailwind.config.js:6SyntaxError: Invalid or unexpected token
Import trace for requested module:
./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet1.rules[3].oneOf[11].use1!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet1.rules[3].oneOf[11].use[2]!./styles/globals.css
./styles/globals.css
我是按 Next.js 和 Tailwind 的常规步骤在全新空项目中安装的,没有使用 tailwindcss/nesting,曾找到过相关讨论但不适用我的情况。
配置文件内容
tailwind.config.js
/** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}", // Or if using `src` directory: "./src/**/*.{js,ts,jsx,tsx}", ], theme: { extend: {}, }, plugins: [], }
postcss.config.js
module.exports = { plugins: { tailwindcss: {},autoprefixer: {}, }, }
package.json
{ "name": "todo", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@next/font": "13.1.3", "eslint": "8.32.0", "eslint-config-next": "13.1.3", "next": "13.1.3", "react": "18.2.0", "react-dom": "18.2.0" }, "devDependencies": { "autoprefixer": "^10.4.13", "postcss": "^8.4.21", "tailwindcss": "^3.2.4" } }
globals.css
@tailwind base; @tailwind components; @tailwind utilities;
可能的解决方案
- 排查配置文件特殊字符:错误指向
tailwind.config.js第6行,尽管代码看起来正常,仍可能存在不可见的全角空格、特殊符号。可以手动重新输入该行内容,或用编辑器显示所有隐藏字符排查异常。 - 修复PostCSS配置语法:
postcss.config.js中tailwindcss: {},和autoprefixer: {},之间缺少空格,规范写法如下,避免解析异常:module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, } - 清除缓存重启项目:删除
.next文件夹和node_modules/.cache目录,重新执行npm install后再启动项目。 - 检查Node.js版本:确认Node.js版本符合Next.js 13.1.3和Tailwind CSS 3.2.4的要求,建议使用16.x或18.x版本。
内容的提问来源于stack exchange,提问作者André Gomes

