上一章講的是腳本裝載相關的loader,這一章見得是腳本格式校驗相關的loaderjavascript
$ mkdir 0x013-linting-loader $ cd 0x013-linting-loader $ npm init -y $ npm install --save-dev webpack $ touch ./src/index.js $ vim webpack.config.js // ./webpack.config.js const path = require('path'); module.exports = { entry : { 'index': ['./src/index.js'], }, output: { path : path.join(__dirname, 'dist'), filename: '[name].bundle.js' } ;
eslint
校驗js格式(這份配置是偷vue
的)安裝依賴包html
cnpm install --save-dev eslint eslint-loader eslint-config-standard eslint-friendly-formatter eslint-plugin-html eslint-plugin-import eslint-plugin-node eslint-plugin-promis eslint-plugin-standard
修改配置文件vue
./webpack.config.js const path = require('path'); module.exports = { entry : { 'index': ['./src/index.js'], }, output: { path : path.join(__dirname, 'dist'), filename: '[name].bundle.js' }, module: { rules: [ { test : /\.js$/, exclude: /node_modules/, enforce: "pre", include: [path.resolve(__dirname, 'src')], loader : "eslint-loader", options: { formatter: require('eslint-friendly-formatter') } } ] } } ;
添加eslint
配置文件java
// .eslintrc.js module.exports = { root : true, parser : 'babel-eslint', parserOptions: { sourceType: 'module' }, env : { browser: true, }, // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style extends : 'standard', // required to lint *.vue files plugins : [ 'html' ], // add your custom rules here 'rules' : { // allow paren-less arrow functions 'arrow-parens' : 0, // allow async-await 'generator-star-spacing': 0, // allow debugger during development 'no-debugger' : 0 } } // .eslintignore dist/*.js // ./.editconfig root = true [*] charset = utf-8 indent_style = space indent_size = 2 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true
編寫測試代碼node
let name="張三"
打包webpack
$ webpack # 輸出 ERROR in ./src/index.js ✘ http://eslint.org/docs/rules/no-multi-spaces Multiple spaces found before 'name' src/index.js:1:6 let name="張三" ^ ✘ http://eslint.org/docs/rules/no-unused-vars 'name' is assigned a value but never used src/index.js:1:6 let name="張三" ^ ✘ http://eslint.org/docs/rules/space-infix-ops Infix operators must be spaced src/index.js:1:10 let name="張三" ^ ✘ http://eslint.org/docs/rules/quotes Strings must use singlequote src/index.js:1:11 let name="張三" ^ ✘ 4 problems (4 errors, 0 warnings)
這裏爆出4個問題git
let
和name
之間只能有一個空格github
name
變量沒有使用過web
張三
前邊沒有空格npm
張三
使用了雙引號,應該用單引號
修復
let name = '張三' console.log(name)
再次打包
$ webpack # 輸出 Hash: 4014a2bcb0ede78b2270 Version: webpack 3.8.1 Time: 616ms Asset Size Chunks Chunk Names index.bundle.js 2.63 kB 0 [emitted] index [0] multi ./src/index.js 28 bytes {0} [built] [2] ./src/index.js 34 bytes {0} [built]
更多配置,請查閱eslint文檔