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 // Allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, '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... // Do not allow console.logs etc...
'no-console': 2, 'no-console': 2,
'space-before-function-paren': [2, { 'space-before-function-paren': [2, {

View File

@ -13,7 +13,7 @@ import axios from 'axios'
export default { export default {
async asyncData({ params }) { async asyncData({ params }) {
// We can use async/await ES6 feature // 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 } return { post: data }
}, },
head() { head() {

View File

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

View File

@ -1,4 +1,4 @@
export default function (ctx) { 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) ctx.isMobile = /mobile/i.test(userAgent)
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -142,7 +142,7 @@ export default class WebpackBaseConfig {
exclude: (file) => { exclude: (file) => {
// not exclude files outside node_modules // not exclude files outside node_modules
if (/node_modules/.test(file)) { 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 // item in transpile can be string or regex object
if (module.test(file)) { if (module.test(file)) {
return false return false

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,7 +18,7 @@ describe('dynamic routes', () => {
routerFile.indexOf('['), routerFile.indexOf('['),
routerFile.lastIndexOf(']') + 1 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 // pages/test/index.vue
expect(routes[0].path).toBe('/test') expect(routes[0].path).toBe('/test')
expect(routes[0].name).toBe('test') expect(routes[0].name).toBe('test')

View File

@ -23,7 +23,7 @@ describe('error', () => {
}) })
test('/404 should display an error too', async () => { 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) expect(error.message.includes('This page could not be found')).toBe(true)
}) })

View File

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

View File

@ -26,7 +26,7 @@ describe('nuxt', () => {
}) })
return new Builder(nuxt).build().catch((err) => { 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('No `pages` directory found')).toBe(true)
expect(s.includes('Did you mean to run `nuxt` in the parent (`../`) directory?')).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 // We strictly compare <foorbar>{id}</foorbar> section
// Because other response parts such as window.__NUXT may be different resulting false positive passes. // Because other response parts such as window.__NUXT may be different resulting false positive passes.
const uniqueTest = async (url) => { const uniqueTest = async (url) => {
let results = [] const results = []
await Utils.parallel(range(5), async () => { await Utils.parallel(range(5), async () => {
let { html } = await nuxt.renderRoute(url) const { html } = await nuxt.renderRoute(url)
let foobar = match(FOOBAR_REGEX, html) const foobar = match(FOOBAR_REGEX, html)
results.push(parseInt(foobar)) results.push(parseInt(foobar))
}) })
let isUnique = uniq(results).length === results.length const isUnique = uniq(results).length === results.length
if (!isUnique) { if (!isUnique) {
/* eslint-disable no-console */ /* eslint-disable no-console */
@ -44,13 +44,13 @@ const uniqueTest = async (url) => {
// Or pending promises/sockets and function calls. // Or pending promises/sockets and function calls.
// Related issue: https://github.com/nuxt/nuxt.js/issues/1354 // Related issue: https://github.com/nuxt/nuxt.js/issues/1354
const stressTest = async (_url, concurrency = 2, steps = 4) => { const stressTest = async (_url, concurrency = 2, steps = 4) => {
let statusCodes = {} const statusCodes = {}
await Utils.sequence(range(steps), async () => { await Utils.sequence(range(steps), async () => {
await Utils.parallel(range(concurrency), 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 // Status Code
let code = response.statusCode const code = response.statusCode
if (!statusCodes[code]) { if (!statusCodes[code]) {
statusCodes[code] = 0 statusCodes[code] = 0
} }

View File

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

View File

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