调试网站发现控制台出现了一句cdn.tailwindcss.com should not be used in production. To use Tailwind CSS in production, install it as a PostCSS plugin or use the Tailwind CLI: https://tailwindcss.com/docs/installation,然后去tailwindcss installation上仔细看了下CDN引入的描述:

Use the Play CDN to try Tailwind right in the browser without any build step. The Play CDN is designed for development purposes only, and is not the best choice for production.

也就是说CDN建议在开发环境下使用。本网站的开发没有引入任何node.js的环境和依赖,tailwindcss提供的安装指南中基本都是使用npx或者框架的情况,在几个CDN站点上搜索cdn引入无果后,最终在github的release页面上找到了tailwindcss的应用程序。

tailwindcss的应用程序一开始我也不知道该如何使用,搜索一番后也没有相关的描述,双击打开后弹出一个terminal然后以几乎察觉不到的速度关掉了,这也说明这个程序是需要在命令行中运行的,运行后出现如下的帮助信息。

PS D:\> .\tailwindcss-windows-x64.exe

tailwindcss v3.4.17

Usage:
   tailwindcss [--input input.css] [--output output.css] [--watch] [options...]
   tailwindcss init [--full] [--postcss] [options...]

Commands:
   init [options]

Options:
   -i, --input              Input file
   -o, --output             Output file
   -w, --watch              Watch for changes and rebuild as needed
   -p, --poll               Use polling instead of filesystem events when watching
       --content            Content paths to use for removing unused classes
       --postcss            Load custom PostCSS configuration
   -m, --minify             Minify the output
   -c, --config             Path to a custom config file
       --no-autoprefixer    Disable autoprefixer
   -h, --help               Display usage information

这也和tailwindcss安装指南中的Tailwind Cli部分大体一致了。

将tailwindcss应用程序导入到PATH环境中,然后在项目根目录中运行tailwindcss init --full初始化tailwindcss.config.js,执行成功后项目根目录中会出现tailwindcss.config.js文件。

然后在tailwindcss.config.js的content中写入需要扫描的文件路径规则,例如:content: ["./src/**/*.{gohtml,html,js}"]

创建一个带有tailwind指令的css文件,教程的文件位于项目目录的/src/input.css,这个根据实际情况来处理即可,写入如下内容:

@tailwind base;
@tailwind components;
@tailwind utilities;

执行tailwindcss -i ./src/input.css -o ./src/output.css --watch,将会在当前项目的src目录中生成output.css文件,这个文件也是针对生产环境下的tailwind最终文件。在开发环境中,添加--watch参数用于及时更新output.css,若是直接输出output.css,则不需要使用--watch参数。

最后在html页面中引入output.css,完成tailwindcss生产环境的处理。

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="./output.css" rel="stylesheet">
</head>
<body>
  <h1 class="text-3xl font-bold underline">
    Hello world!
  </h1>
</body>
</html>

 

为什么tailwindcss不建议CDN引入?

网上找到的部分结论说原始的CDN引入,tailwindcss的样式文件非常大,大约有1.2M,但是实际上目前的3.4.17版本根据CDN Play指南引入tailwindcss,实际引入的是一个javascript文件,文件也不算太大,不过这个js引入最大问题还是有个警告总是出现在控制台。这也是本文的初衷,解决控制台的警告,不过按照这个流程操作下来,output.css只有23KB,这还是没有进行压缩的情况下,而cdn的js文件有397KB。