在 Angular 中从 Typescript 文件配置 Tailwind 主题
Posted
技术标签:
【中文标题】在 Angular 中从 Typescript 文件配置 Tailwind 主题【英文标题】:Configuring Tailwind theme from Typescript file in Angular 【发布时间】:2022-01-02 20:35:32 【问题描述】:我想在 .ts 文件中设置 Tailwind 主题,以利用在我的 Angular 服务中键入和重用我的打字稿代码中定义的值。
我使用 Angular CLI 13.1 创建了项目:
// package.json
"name": "test-project-tailwind",
"type": "module",
"version": "0.0.0",
"scripts":
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
,
"private": true,
"dependencies":
"@angular/animations": "~13.1.1",
"@angular/common": "~13.1.1",
"@angular/compiler": "~13.1.1",
"@angular/core": "~13.1.1",
"@angular/forms": "~13.1.1",
"@angular/platform-browser": "~13.1.1",
"@angular/platform-browser-dynamic": "~13.1.1",
"@angular/router": "~13.1.1",
"rxjs": "~6.6.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
,
"devDependencies":
"@angular-devkit/build-angular": "~13.1.2",
"@angular/cli": "~13.1.2",
"@angular/compiler-cli": "~13.1.1",
"@types/jasmine": "~3.8.0",
"@types/node": "^12.11.1",
"autoprefixer": "10.4.0",
"jasmine-core": "~3.8.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"postcss": "8.4.5",
"tailwindcss": "3.0.5",
"typescript": "~4.5.4"
我安装了tailwindcss:
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
npx tailwindcss init
我设置了顺风配置:
// tailwind.config.js
import theme from 'src/theme/theme'
module.exports =
darkMode: false,
theme: theme
// src/theme/theme.ts
export default
colors:
blue: 'blue',
red: 'red'
,
然后我在ng serve
收到以下错误:
发生未处理的异常:必须使用导入来加载 ES 模块:project-path\tailwind.config.js
不支持 ES 模块的 require()。
project-path\node_modules\tailwindcss\lib\index.js 的 project-path\tailwind.config.js 的 require() 是一个 ES 模块文件,因为它是一个 .js 文件,其最近的父 package.json 包含 "type": "module" 将包范围内的所有 .js 文件定义为 ES 模块。 而是将 tailwind.config.js 重命名为以 .cjs 结尾,将需要的代码更改为使用 import(),或者从 project-path\package.json 中删除 "type": "module"。
知道我怎么能做到这一点吗?
【问题讨论】:
您是否尝试将您的tailwind.config.js
改为以.cjs
结尾?
是的,文件只是没有加载。
你能发一下你的package.json
您在哪里使用require()
?比如在你的全局css文件或者theme.ts
?
不,从project-path\node_modules\tailwindcss\lib\index.js
调用require()
来加载我的配置文件tailwind.config.js
。
【参考方案1】:
我也遇到了这个问题,虽然我尝试了几件事(即使用.cjs
文件),但我没有任何运气。我终于通过简单地删除type: module
来完成这项工作,这不是最理想的事情。我想我可能在我的 package.json 中明确设置了 type: module
只是因为我认为这是一个最佳实践,但它不是由 angular 本身设置的。如果你只是运行ng new
,模块类型没有显式设置(因此默认为 commonjs)。
就我而言,我还必须安装 postcss,因为 tailwind 至少需要 8.0 或更高版本。
【讨论】:
我尝试删除type: module
,但在运行ng serve
时,我在tailwind.config.js` lign 1 中得到SyntaxError: Cannot use import statement outside a module
。知道我可能缺少什么吗?
我现在看到了你的配置,你正在使用import
作为src/theme/theme
。您可以将src/theme/theme
设为module.exports
,然后使用var theme = require('src/theme/theme')
要求而不是使用导入吗?以上是关于在 Angular 中从 Typescript 文件配置 Tailwind 主题的主要内容,如果未能解决你的问题,请参考以下文章
在 react-native 中从 TypeScript 调用本机函数