如何在Angular11.2.0或更低版本中设置TailwindCSS
如您所知,Tailwind 是一种非常流行的 PostCSS 解决方案。我想在运行版本 11.2.0 或旧版本的 Angular 应用程序中添加 TailwindCSS。我怎么能这样做?
我决定发布并回答我自己的问题,因为这是我最近在 Angular 社区看到的一个非常受欢迎的问题
回答
在 Angular 11.2.0 中设置 TailwindCSS
-
安装
npm install -D tailwindcss -
安装 TailwindCSS 插件(可选):
-
npm i @tailwindcss/typography -
npm i @tailwindcss/forms
- 在工作区或项目根目录中创建 TailwindCSS 配置文件。命名该配置文件
tailwind.config.js
它应该是这样的:
module.exports = {
prefix: '',
purge: {
content: [
'./src/**/*.{html,ts}',
]
},
darkMode: 'class', // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [require('@tailwindcss/forms'),require('@tailwindcss/typography')],
};
- 在你的 styles.scss 文件中添加以下 TailwindCSS 导入
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
如果您使用的是 CSS 而不是 SCSS,您的文件应如下所示:
@tailwind base;
@tailwind components;
@tailwind utilities;
确保 Angular 中的 TailwindCSS 正常工作
转到任何一个组件并编写以下内容:
<button
class="py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-red-400">Hello</button>
现在运行ng serve,您应该会看到以下按钮
如何在生产中清除 TailwindCSS
如果我们不清除,由于 TailwindCSS 为您添加的所有 CSS 类,我们的 CSS 可能会非常繁重。如果清除,所有未使用的类将被删除。
我想在 Angular 11.2.0 中进行清除的方式如下:
A) 这是我的首选方式。将此添加到您的构建脚本中NODE_ENV=production ng build --prod
,您的 tailwind.config.js 文件应如下所示。
purge: {
enabled: process.env.NODE_ENV === 'production',
content: [
'./src/**/*.{html,ts}',
]
},
B)在您tailwind.config.js file的enabled属性中,您可以将属性内的purge属性设置为true. 这将一直运行清除,请注意这一点。
....
prefix: '',
purge: {
enabled: true,
content: [
'./src/**/*.{html,ts}',
]
},
....
然后你可以运行ng build --prod,你会看到你的包变小了。
净化前
净化后
要了解有关使用 TailwindCSS 的 Angular(11.2.0 或更旧版本)的更多信息,请查看我的文章
https://dev.to/angular/setup-tailwindcss-in-angular-the-easy-way-1i5l