JavaScript 可以使用多种方法来格式化 CSS 样式代码,以下是其中两种:1. 使用第三方库:第三方库如 Prettier、ESLint 或 Beautify.js 提供了格式化代码的功能,包括 CSS 样式代码。这些库具有自定义选项,可个性化 CSS 样式代码格式。例如,使用 Prettier 对 CSS 样式代码进行格式化:const prettier = require('prettier');const cssCode =.selector {property: value;};const formattedCode = prettier.format(cssCode, {parser: 'css',tabWidth: 2,printWidth: 80,// 其他选项});console.log(formattedCode);2. 自行编写格式化代码:可以编写代码以自定义格式化 CSS 样式代码。一种方法是使用正则表达式与字符串操作。示例代码用于对 CSS 样式代码进行缩进:function indentCSS(cssCode) {let indentLevel = 0;let indentSize = 2;return cssCode.replace(/s*{s*/g, ' {n').replace(/;(S)/g, ';n$1').replace(/}s*/g, 'n}n').replace(/^/gm, () => ' '.repeat(indentSize * indentLevel++));}该函数首先在每个选择器后插入换行符,然后将每个分号后的值移动至新行,并在每个左括号前插入换行符。最后,利用 replace() 方法和回调函数加入适当数量的空格实现缩进。