eslint: Prefer const over let (#3650)

This commit is contained in:
Alexander Lichter 2018-08-08 12:54:05 +02:00 committed by Sébastien Chopin
parent 4db5c7804d
commit 52d9629bac
25 changed files with 69 additions and 64 deletions

View File

@ -47,6 +47,12 @@ module.exports = {
// Allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
// Prefer const over let
"prefer-const": ["error", {
"destructuring": "any",
"ignoreReadBeforeAssign": false
}],
// Do not allow console.logs etc...
'no-console': 2,
'space-before-function-paren': [2, {

View File

@ -13,7 +13,7 @@ import axios from 'axios'
export default {
async asyncData({ params }) {
// We can use async/await ES6 feature
let { data } = await axios.get(`https://jsonplaceholder.typicode.com/posts/${params.id}`)
const { data } = await axios.get(`https://jsonplaceholder.typicode.com/posts/${params.id}`)
return { post: data }
},
head() {

View File

@ -7,7 +7,7 @@ const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000
// Import and set Nuxt.js options
let config = require('./nuxt.config.js')
const config = require('./nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
const nuxt = new Nuxt(config)

View File

@ -1,4 +1,4 @@
export default function (ctx) {
let userAgent = ctx.req ? ctx.req.headers['user-agent'] : navigator.userAgent
const userAgent = ctx.req ? ctx.req.headers['user-agent'] : navigator.userAgent
ctx.isMobile = /mobile/i.test(userAgent)
}

View File

@ -35,7 +35,7 @@ nStoriesOf({ Logo }, 'Logo ')
}))
.addVT('with App layout', '<logo :data="{ } "/>')
.addVT('with a knob', () => {
let data = JSON.stringify(
const data = JSON.stringify(
object('Data', {
name: 'Apple',
count: 132

View File

@ -37,7 +37,7 @@ const vtmp = (cmp, cmpStr) => ({
* @param {*} params
*/
const nStoriesOf = (cmp, name = Object.keys(cmp)[0], params = {}) => {
let x = storiesOf(name, module)
const x = storiesOf(name, module)
.addDecorator(centered)
.addDecorator(withKnobs)

View File

@ -11,7 +11,7 @@ export default function () {
this.nuxt.hook('close', () => new Promise(server.close))
// Add socket.io events
let messages = []
const messages = []
io.on('connection', (socket) => {
socket.on('last-messages', function (fn) {
fn(messages.slice(-50))

View File

@ -41,7 +41,7 @@ export default {
methods: {
sendMessage() {
if (!this.message.trim()) return
let message = {
const message = {
date: new Date().toJSON(),
text: this.message.trim()
}

View File

@ -12,7 +12,7 @@ const server = http.createServer(app)
const io = SocketIO(server)
// We instantiate Nuxt.js with the options
let config = require('./nuxt.config.js')
const config = require('./nuxt.config.js')
config.dev = !isProd
const nuxt = new Nuxt(config)
@ -28,7 +28,7 @@ server.listen(port, '0.0.0.0')
console.log('Server listening on localhost:' + port) // eslint-disable-line no-console
// Socket.io
let messages = []
const messages = []
io.on('connection', (socket) => {
socket.on('last-messages', function (fn) {
fn(messages.slice(-50))

View File

@ -113,7 +113,7 @@ export default class Builder {
this._nuxtPages = typeof this.options.build.createRoutes !== 'function'
if (this._nuxtPages) {
if (!fsExtra.existsSync(path.join(this.options.srcDir, this.options.dir.pages))) {
let dir = this.options.srcDir
const dir = this.options.srcDir
if (fsExtra.existsSync(path.join(this.options.srcDir, '..', this.options.dir.pages))) {
throw new Error(
`No \`${this.options.dir.pages}\` directory found in ${dir}. Did you mean to run \`nuxt\` in the parent (\`../\`) directory?`
@ -215,7 +215,7 @@ export default class Builder {
})
let hasErrorLayout = false
layoutsFiles.forEach((file) => {
let name = file
const name = file
.split('/')
.slice(1)
.join('/')

View File

@ -96,7 +96,7 @@ export default class Generator {
}
async generateRoutes(routes) {
let errors = []
const errors = []
// Start generate process
while (routes.length) {
@ -139,7 +139,7 @@ export default class Generator {
}
async afterGenerate() {
let { fallback } = this.options.generate
const { fallback } = this.options.generate
// Disable SPA fallback if value isn't true or a string
if (fallback !== true && typeof fallback !== 'string') return
@ -193,7 +193,7 @@ export default class Generator {
}
decorateWithPayloads(routes, generateRoutes) {
let routeMap = {}
const routeMap = {}
// Fill routeMap for known routes
routes.forEach((route) => {
routeMap[route] = { route, payload: null }

View File

@ -142,7 +142,7 @@ export default class WebpackBaseConfig {
exclude: (file) => {
// not exclude files outside node_modules
if (/node_modules/.test(file)) {
for (let module of [/\.vue\.js/].concat(this.options.build.transpile)) {
for (const module of [/\.vue\.js/].concat(this.options.build.transpile)) {
// item in transpile can be string or regex object
if (module.test(file)) {
return false

View File

@ -55,8 +55,8 @@ export default class PostcssConfig {
configFromFile() {
// Search for postCSS config file and use it if exists
// https://github.com/michael-ciniawsky/postcss-load-config
for (let dir of [this.srcDir, this.rootDir]) {
for (let file of [
for (const dir of [this.srcDir, this.rootDir]) {
for (const file of [
'postcss.config.js',
'.postcssrc.js',
'.postcssrc',

View File

@ -99,7 +99,7 @@ export const chainFn = function chainFn(base, fn) {
if (baseResult === undefined) {
baseResult = arguments[0]
}
let fnResult = fn.call(
const fnResult = fn.call(
this,
baseResult,
...Array.prototype.slice.call(arguments, 1)
@ -139,8 +139,8 @@ const sysSep = _.escapeRegExp(path.sep)
const normalize = string => string.replace(reqSep, sysSep)
export const r = function r() {
let args = Array.prototype.slice.apply(arguments)
let lastArg = _.last(args)
const args = Array.prototype.slice.apply(arguments)
const lastArg = _.last(args)
if (lastArg.indexOf('@') === 0 || lastArg.indexOf('~') === 0) {
return wp(lastArg)
@ -150,8 +150,8 @@ export const r = function r() {
}
export const relativeTo = function relativeTo() {
let args = Array.prototype.slice.apply(arguments)
let dir = args.shift()
const args = Array.prototype.slice.apply(arguments)
const dir = args.shift()
// Keep webpack inline loader intact
if (args[0].indexOf('!') !== -1) {
@ -161,7 +161,7 @@ export const relativeTo = function relativeTo() {
}
// Resolve path
let _path = r(...args)
const _path = r(...args)
// Check if path is an alias
if (_path.indexOf('@') === 0 || _path.indexOf('~') === 0) {
@ -201,12 +201,12 @@ export const flatRoutes = function flatRoutes(router, _path = '', routes = []) {
function cleanChildrenRoutes(routes, isChild = false) {
let start = -1
let routesIndex = []
const routesIndex = []
routes.forEach((route) => {
if (/-index$/.test(route.name) || route.name === 'index') {
// Save indexOf 'index' key in name
let res = route.name.split('-')
let s = res.indexOf('index')
const res = route.name.split('-')
const s = res.indexOf('index')
start = start === -1 || s < start ? s : start
routesIndex.push(res)
}
@ -214,13 +214,13 @@ function cleanChildrenRoutes(routes, isChild = false) {
routes.forEach((route) => {
route.path = isChild ? route.path.replace('/', '') : route.path
if (route.path.indexOf('?') > -1) {
let names = route.name.split('-')
let paths = route.path.split('/')
const names = route.name.split('-')
const paths = route.path.split('/')
if (!isChild) {
paths.shift()
} // clean first / for parents
routesIndex.forEach((r) => {
let i = r.indexOf('index') - start // children names
const i = r.indexOf('index') - start // children names
if (i < paths.length) {
for (let a = 0; a <= i; a++) {
if (a === i) {
@ -246,15 +246,15 @@ function cleanChildrenRoutes(routes, isChild = false) {
}
export const createRoutes = function createRoutes(files, srcDir, pagesDir) {
let routes = []
const routes = []
files.forEach((file) => {
let keys = file
const keys = file
.replace(RegExp(`^${pagesDir}`), '')
.replace(/\.(vue|js)$/, '')
.replace(/\/{2,}/g, '/')
.split('/')
.slice(1)
let route = { name: '', path: '', component: r(srcDir, file) }
const route = { name: '', path: '', component: r(srcDir, file) }
let parent = routes
keys.forEach((key, i) => {
// remove underscore only, if its the prefix
@ -266,7 +266,7 @@ export const createRoutes = function createRoutes(files, srcDir, pagesDir) {
: sanitizedKey
route.name += key === '_' ? 'all' : ''
route.chunkName = file.replace(/\.(vue|js)$/, '')
let child = _.find(parent, { name: route.name })
const child = _.find(parent, { name: route.name })
if (child) {
child.children = child.children || []
parent = child.children

View File

@ -89,9 +89,9 @@ async function readSource(frame) {
]
// Scan filesystem for real source
for (let pathDir of searchPath) {
let fullPath = path.resolve(pathDir, frame.fileName)
let source = await fs.readFile(fullPath, 'utf-8').catch(() => null)
for (const pathDir of searchPath) {
const fullPath = path.resolve(pathDir, frame.fileName)
const source = await fs.readFile(fullPath, 'utf-8').catch(() => null)
if (source) {
frame.contents = source
frame.fullPath = fullPath

View File

@ -205,7 +205,7 @@ export default class Nuxt {
return _path
}
for (let ext of this.options.extensions) {
for (const ext of this.options.extensions) {
if (fs.existsSync(_path + '.' + ext)) {
return _path + '.' + ext
}

View File

@ -61,23 +61,22 @@ export default class Renderer {
}
async loadResources(_fs = fs) {
let distPath = path.resolve(this.options.buildDir, 'dist')
let updated = []
const distPath = path.resolve(this.options.buildDir, 'dist')
const updated = []
resourceMap.forEach(({ key, fileName, transform }) => {
let rawKey = '$$' + key
const rawKey = '$$' + key
const _path = path.join(distPath, fileName)
let rawData, data
if (!_fs.existsSync(_path)) {
return // Resource not exists
}
rawData = _fs.readFileSync(_path, 'utf8')
const rawData = _fs.readFileSync(_path, 'utf8')
if (!rawData || rawData === this.resources[rawKey]) {
return // No changes
}
this.resources[rawKey] = rawData
data = transform(rawData)
const data = transform(rawData)
/* istanbul ignore if */
if (!data) {
return // Invalid data ?
@ -371,7 +370,7 @@ export default class Renderer {
const cspScriptSrcHashSet = new Set()
if (this.options.render.csp) {
const { hashAlgorithm } = this.options.render.csp
let hash = crypto.createHash(hashAlgorithm)
const hash = crypto.createHash(hashAlgorithm)
hash.update(serializedSession)
cspScriptSrcHashSet.add(`'${hashAlgorithm}-${hash.digest('base64')}'`)
}
@ -414,7 +413,7 @@ export default class Renderer {
throw e
}
}
let options = {
const options = {
resources: 'usable', // load subresources (https://github.com/tmpvar/jsdom#loading-subresources)
runScripts: 'dangerously',
beforeParse(window) {
@ -436,7 +435,7 @@ export default class Renderer {
)
/* istanbul ignore if */
if (!nuxtExists) {
let error = new Error('Could not load the nuxt app')
const error = new Error('Could not load the nuxt app')
error.body = window.document.body.innerHTML
throw error
}

View File

@ -29,7 +29,7 @@ describe('basic browser', () => {
test('/noloading', async () => {
const { hook } = await page.nuxt.navigate('/noloading')
let loading = await page.nuxt.loadingData()
const loading = await page.nuxt.loadingData()
expect(loading.show).toBe(true)
await hook
expect(loading.show).toBe(true)

View File

@ -18,7 +18,7 @@ describe('dynamic routes', () => {
routerFile.indexOf('['),
routerFile.lastIndexOf(']') + 1
)
let routes = eval('( ' + routerFile + ')') // eslint-disable-line no-eval
const routes = eval('( ' + routerFile + ')') // eslint-disable-line no-eval
// pages/test/index.vue
expect(routes[0].path).toBe('/test')
expect(routes[0].name).toBe('test')

View File

@ -23,7 +23,7 @@ describe('error', () => {
})
test('/404 should display an error too', async () => {
let { error } = await nuxt.renderRoute('/404')
const { error } = await nuxt.renderRoute('/404')
expect(error.message.includes('This page could not be found')).toBe(true)
})

View File

@ -45,12 +45,12 @@ describe('module', () => {
// })
test('Middleware', async () => {
let response = await rp(url('/api'))
const response = await rp(url('/api'))
expect(response).toBe('It works!')
})
test('Hooks - Use external middleware before render', async () => {
let response = await rp(url('/use-middleware'))
const response = await rp(url('/use-middleware'))
expect(response).toBe('Use external middleware')
})

View File

@ -26,7 +26,7 @@ describe('nuxt', () => {
})
return new Builder(nuxt).build().catch((err) => {
let s = String(err)
const s = String(err)
expect(s.includes('No `pages` directory found')).toBe(true)
expect(s.includes('Did you mean to run `nuxt` in the parent (`../`) directory?')).toBe(true)
})

View File

@ -19,15 +19,15 @@ const url = route => 'http://localhost:' + port + route
// We strictly compare <foorbar>{id}</foorbar> section
// Because other response parts such as window.__NUXT may be different resulting false positive passes.
const uniqueTest = async (url) => {
let results = []
const results = []
await Utils.parallel(range(5), async () => {
let { html } = await nuxt.renderRoute(url)
let foobar = match(FOOBAR_REGEX, html)
const { html } = await nuxt.renderRoute(url)
const foobar = match(FOOBAR_REGEX, html)
results.push(parseInt(foobar))
})
let isUnique = uniq(results).length === results.length
const isUnique = uniq(results).length === results.length
if (!isUnique) {
/* eslint-disable no-console */
@ -44,13 +44,13 @@ const uniqueTest = async (url) => {
// Or pending promises/sockets and function calls.
// Related issue: https://github.com/nuxt/nuxt.js/issues/1354
const stressTest = async (_url, concurrency = 2, steps = 4) => {
let statusCodes = {}
const statusCodes = {}
await Utils.sequence(range(steps), async () => {
await Utils.parallel(range(concurrency), async () => {
let response = await rp(url(_url), { resolveWithFullResponse: true })
const response = await rp(url(_url), { resolveWithFullResponse: true })
// Status Code
let code = response.statusCode
const code = response.statusCode
if (!statusCodes[code]) {
statusCodes[code] = 0
}

View File

@ -8,7 +8,7 @@ describe('utils', () => {
})
test('getContext', () => {
let ctx = Utils.getContext({ a: 1 }, { b: 2 })
const ctx = Utils.getContext({ a: 1 }, { b: 2 })
expect(Utils.getContext.length).toBe(2)
expect(typeof ctx.req).toBe('object')
expect(typeof ctx.res).toBe('object')
@ -17,7 +17,7 @@ describe('utils', () => {
})
test.skip.appveyor('waitFor', async () => {
let s = Date.now()
const s = Date.now()
await Utils.waitFor(100)
expect(Date.now() - s >= 100).toBe(true)
await Utils.waitFor()

View File

@ -6,17 +6,17 @@ export default function mockLog(levels = 'all', logger = console) {
levels = [levels]
}
beforeAll(() => {
for (let level of levels) {
for (const level of levels) {
jest.spyOn(logger, level).mockImplementation(() => {})
}
})
beforeEach(() => {
for (let level of levels) {
for (const level of levels) {
logger[level].mockClear()
}
})
afterAll(() => {
for (let level of levels) {
for (const level of levels) {
logger[level].mockRestore()
}
})