vue项目webpack2.x集成stylelint

815 阅读1分钟

1.使用cnpm/npm安装以下三个包:

npm i -D stylelint-webpack-plugin stylelint-config-standard

注意:

  1. webpack为2.x版本时,使用stylelint-webpack-plugin@1.0.3会报错,降为0.10.5后功能正常。
  2. webpack为4.x版本是,使用stylelint-webpack-plugin@1.0.3功能正常。

2.找到webpack(build/webpack.dev.conf.js)的配置文件:

文件开始引入插件

const StylelintPlugin = require('stylelint-webpack-plugin');

3.再找到plugin配置项,添加如下代码:

plugins: [
    new webpack.DefinePlugin({
        'process.env': config.dev.env
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new HtmlWebpackPlugin({
        filename: 'index.html',
        template: 'index.html',
        inject: true
    }),
    // 添加以下代码-开始
    new StylelintPlugin({
        context: 'src',
        files: ['**/*.{html,vue,css,less}'],
        fix: false,
        cache: true,
        failOnError: false
    }),
    // 需添加代码-结束
    new FriendlyErrorsPlugin(),
]

4.在项目根目录下,添加.stylelintrc.js文件,然后配置规则,以下是我的配置规则:

// .stylelintrc.js
// stylelint规则配置

module.exports = {
    extends: 'stylelint-config-standard',
    rules: {
        indentation: 4, // 4个空格缩进
        'color-no-invalid-hex': true, // 禁止使用无效的十六进制颜色
        'function-calc-no-invalid': true, // 禁止在calc函数内使用无效的表达式
        'rule-empty-line-before': null,
        'color-hex-length': 'short',
        'color-hex-case': 'lower',
        'unit-whitelist': ['em', 'rem', '%', 's', 'px'],
        'declaration-colon-newline-after': null,
        'declaration-no-important': true // 禁止!important在声明中使用
    }
};