vwe开发之代码检测
开发过程中为了统一代码格式,需要在build的时候对代码检测,这个时候需要使用到ESLint Code Linting
- 安装依赖:
npm install --save-dev eslint babel-eslint eslint-loader
- 在根目录下生成文件.eslintrc.js,代码如下:
module.exports = {
"plugins": [ "react" ],
"extends": [
"eslint:recommended",
"plugin:react/recommended"
],
"parser": "babel-eslint"
};
然后更新 webpack.dev.config.js代码如下:
const path = require('path')
const webpack = require('webpack')
const HtmlWebPackPlugin = require('html-webpack-plugin')
module.exports = {
entry: {
main: ['webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', './src/index.js']
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js'
},
mode: 'development',
target: 'web',
devtool: 'source-map',
module: {
rules: [
//新加
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
emitWarning: true,
failOnError: false,
failOnWarning: false
}
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
// Loads the javacript into html template provided.
// Entry point is set below in HtmlWebPackPlugin in Plugins
test: /\.html$/,
use: [
{
loader: "html-loader",
//options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/html/index.html",
filename: "./index.html",
excludeChunks: [ 'server' ]
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
]
}
我们添加了rule:
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
emitWarning: true,
failOnError: false,
failOnWarning: false
}
},
然后在 ./src/index.js中添加下列的eslint行禁止(其实不是很懂啥意思)
module.hot.accept() // eslint-disable-line no-undef
这个时候重新编译
npm run buildDev
这个时候,你可能会出现缺少某些插件如‘eslint-plugin-react’啥的,按提示安装就好了
npm i --save-de eslint-plugin-import eslint-plugin-node eslint-plugin-promise eslint-plugin-react eslint-plugin-standard
重新编译,不出意外的话,会出现下面的两个错误
1:27 error Unexpected console statement no-console
1:27 error 'console' is not defined no-undef
✖ 2 problems (2 errors, 0 warnings)
Console 语句在生产环境是不允许的,所以eslint指出来,为了禁止eslint,只需要添加下面的代码到logger.js中
/* eslint-disable */
//代码
再次编译,如果还是出现如下的异常
7:11 error 'module' is not defined no-undef
修改代码如下:
// eslint-disable-next-line
if(typeof(module.hot) !== 'undefined') {
// eslint-disable-next-line
module.hot.accept()
}
重新编译,理论上就ok了。