灏天阁

vue3.2/Vite/Ts4: 配置 stylelint

· Yin灏

stylelint 为 css 的 lint 工具,可以格式化 css 代码,检查 css 语法错误与不合理的写法,指定 css 书写顺序等。

我们项目中使用 scss 作为预处理器,安装以下依赖:

pnpm add sass sass-loader stylelint postcss postcss-scss postcss-html stylelint-config-prettier stylelint-config-recess-order stylelint-config-recommended-scss stylelint-config-standard stylelint-config-standard-vue stylelint-scss stylelint-order stylelint-config-standard-scss -D

.stylelintrc.cjs 配置文件

  • 官网:https://stylelint.bootcss.com
module.exports = {
	extends: [
		'stylelint-config-standard',
		'stylelint-config-html/vue',
		'stylelint-config-standard-scss',
		'stylelint-config-recommended-vue/scss',
		'style-config-recess-order',
		'stylelint-config-prettier'
	],
	overrides: [
		{
			files: ['**/*.(scss|css|vue|html)'],
			customSyntax: 'postcss-scss'
		},
		{
			files: ['**/*.(html|vue)'],
			customSyntax: 'postcss-html'
		}
	],
	ignoreFiles: [
		'**/*.js',
		'**/*.jsx',
		'**/*.tsx',
		'**/*ts',
		'**/*.json',
		'**/*.md',
		'**/*.yaml'
	],
	rules: {
		'value-keyword-case': null,
		'no-descending-specificity': null,
		'function-url-quotes': always,
		'no-empty-source': null,
		'selector-class-pattern': null,
		'property-no-unknown': null,
		'block-opening-brace-space-before': 'always',
		'value-no-vendor-prefix': null,
		'property-no-vendor-prefix': null,
		'selector-pseudo-class-no-unknown': [
			true,
			{
				ignorePseudoClass: ['global', 'v-deep', 'deep']
			}
		]
	}
}

.stylelintignore 忽略文件

/node_modules/*
/dist/*
/html/*
/public/*

运行脚本

//...
"scripts": {
	"lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix"
}
//...

最后配置统一的 prettier 来格式化我们的 js、css、html 代码

//...
"scripts": {
	"dev": "vite --open",
	"build": "vue-tsc && vite build",
	"preview": "vite preview",
	"lint": "eslint lint",
	"fix": "eslint src --fix",
	// 统一格式化 html,js,css
	"format": "prettier --write \"./**/*.{html,vue,ts,js,json,md}\"",
	"lint:eslint": "eslint src/**/*.{ts,vue} --cache --fix",
	"lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix"
}
//...

当我们以运行 pnpm run format 的时候,会把代码直接格式化。

- Book Lists -