How to stop TailwindCSS from deleting unused styles
When using TailwindCSS, its tool removes all unused styles in production to minimize the final file size, ensuring loading efficiency. However, there may be cases where we need to retain styles we anticipate using in the future, or styles with dynamic class names that cannot be directly identified as 'used' during the build. To prevent these styles from being removed, we can adopt the following strategies:1. Using TailwindCSS's OptionIn TailwindCSS's configuration file, the option allows us to explicitly specify which styles should not be removed. For example, if we know that certain dynamically generated class names may be used when users interact with the page, we can pre-add these class names to the .In this example, and will always be retained, and all class names starting with will not be removed.2. Indirectly Referencing Styles in CodeSometimes, to ensure certain styles are not removed, we can indirectly reference these styles in a JavaScript file within the project. For example, we can create an array or object to store these class names, even if they are not directly used in HTML or components, as their presence prevents them from being removed during the build.3. Configuring PurgeCSSTailwindCSS internally uses PurgeCSS to remove unused styles. We can avoid removing specific styles by configuring PurgeCSS more explicitly. For example, use the and options to add additional retention rules.4. Environment Condition ChecksIn some cases, we may want to retain all styles in the development environment for easier debugging and page design, but still remove unused styles in production. This can be controlled by environment variables to adjust Tailwind's option.Thus, in development, all styles are retained, while in production, only necessary styles and explicitly specified retained styles are included in the build file.By adopting these strategies, we can effectively control TailwindCSS's style filtering behavior, ensuring that necessary styles are not mistakenly removed while maintaining efficiency and performance in production.