diff --git a/.eslintrc.js b/.eslintrc.js index 992b0e3d53..7f66651011 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -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, { diff --git a/examples/async-data/pages/posts/_id.vue b/examples/async-data/pages/posts/_id.vue index d7f33bb081..c444d48c5e 100644 --- a/examples/async-data/pages/posts/_id.vue +++ b/examples/async-data/pages/posts/_id.vue @@ -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() { diff --git a/examples/custom-server/server.js b/examples/custom-server/server.js index 05cd6338cb..f9a353adee 100644 --- a/examples/custom-server/server.js +++ b/examples/custom-server/server.js @@ -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) diff --git a/examples/dynamic-layouts/middleware/mobile.js b/examples/dynamic-layouts/middleware/mobile.js index 276889f41d..179645220b 100644 --- a/examples/dynamic-layouts/middleware/mobile.js +++ b/examples/dynamic-layouts/middleware/mobile.js @@ -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) } diff --git a/examples/storybook/stories/Logo.story.js b/examples/storybook/stories/Logo.story.js index e0ff1ecb61..60d0212fb7 100644 --- a/examples/storybook/stories/Logo.story.js +++ b/examples/storybook/stories/Logo.story.js @@ -35,7 +35,7 @@ nStoriesOf({ Logo }, 'Logo ') })) .addVT('with App layout', '') .addVT('with a knob', () => { - let data = JSON.stringify( + const data = JSON.stringify( object('Data', { name: 'Apple', count: 132 diff --git a/examples/storybook/stories/storybase.js b/examples/storybook/stories/storybase.js index 5cbecc517d..ba2b93a3f2 100644 --- a/examples/storybook/stories/storybase.js +++ b/examples/storybook/stories/storybase.js @@ -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) diff --git a/examples/with-sockets/io/index.js b/examples/with-sockets/io/index.js index 5a951489b3..bcf53592de 100644 --- a/examples/with-sockets/io/index.js +++ b/examples/with-sockets/io/index.js @@ -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)) diff --git a/examples/with-sockets/pages/index.vue b/examples/with-sockets/pages/index.vue index 98d4087638..23d155fcf8 100644 --- a/examples/with-sockets/pages/index.vue +++ b/examples/with-sockets/pages/index.vue @@ -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() } diff --git a/examples/with-sockets/server.js b/examples/with-sockets/server.js index 0e668f3ccb..648f7427e0 100644 --- a/examples/with-sockets/server.js +++ b/examples/with-sockets/server.js @@ -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)) diff --git a/lib/builder/builder.js b/lib/builder/builder.js index 1b47687812..e74bac9f22 100644 --- a/lib/builder/builder.js +++ b/lib/builder/builder.js @@ -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('/') diff --git a/lib/builder/generator.js b/lib/builder/generator.js index 0549f5114f..0bcd060468 100644 --- a/lib/builder/generator.js +++ b/lib/builder/generator.js @@ -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 } diff --git a/lib/builder/webpack/base.js b/lib/builder/webpack/base.js index b78ceb9322..259c0e502d 100644 --- a/lib/builder/webpack/base.js +++ b/lib/builder/webpack/base.js @@ -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 diff --git a/lib/builder/webpack/utils/postcss.js b/lib/builder/webpack/utils/postcss.js index 675d3ba5d5..31f6ec2055 100644 --- a/lib/builder/webpack/utils/postcss.js +++ b/lib/builder/webpack/utils/postcss.js @@ -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', diff --git a/lib/common/utils.js b/lib/common/utils.js index fe22d87f8f..9e29960923 100644 --- a/lib/common/utils.js +++ b/lib/common/utils.js @@ -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 diff --git a/lib/core/middleware/error.js b/lib/core/middleware/error.js index e594a3d4c7..3906bd30a9 100644 --- a/lib/core/middleware/error.js +++ b/lib/core/middleware/error.js @@ -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 diff --git a/lib/core/nuxt.js b/lib/core/nuxt.js index e249dcb6d2..6c66187606 100644 --- a/lib/core/nuxt.js +++ b/lib/core/nuxt.js @@ -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 } diff --git a/lib/core/renderer.js b/lib/core/renderer.js index 30c324e35c..34c66f514b 100644 --- a/lib/core/renderer.js +++ b/lib/core/renderer.js @@ -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 } diff --git a/test/e2e/basic.browser.test.js b/test/e2e/basic.browser.test.js index cad9abdf2b..5581c9cfa6 100644 --- a/test/e2e/basic.browser.test.js +++ b/test/e2e/basic.browser.test.js @@ -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) diff --git a/test/unit/dynamic-routes.test.js b/test/unit/dynamic-routes.test.js index 6d11680444..aca01297e6 100644 --- a/test/unit/dynamic-routes.test.js +++ b/test/unit/dynamic-routes.test.js @@ -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') diff --git a/test/unit/error.test.js b/test/unit/error.test.js index 3a92a3057f..b421f0d0e3 100644 --- a/test/unit/error.test.js +++ b/test/unit/error.test.js @@ -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) }) diff --git a/test/unit/module.test.js b/test/unit/module.test.js index 8120cfcb65..81cb6c7011 100644 --- a/test/unit/module.test.js +++ b/test/unit/module.test.js @@ -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') }) diff --git a/test/unit/nuxt.test.js b/test/unit/nuxt.test.js index 4f5232e220..46395238d9 100644 --- a/test/unit/nuxt.test.js +++ b/test/unit/nuxt.test.js @@ -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) }) diff --git a/test/unit/ssr.test.js b/test/unit/ssr.test.js index 9907554f67..30470d8564 100644 --- a/test/unit/ssr.test.js +++ b/test/unit/ssr.test.js @@ -19,15 +19,15 @@ const url = route => 'http://localhost:' + port + route // We strictly compare {id} 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 } diff --git a/test/unit/utils.test.js b/test/unit/utils.test.js index 55996ababb..a3b2c63375 100644 --- a/test/unit/utils.test.js +++ b/test/unit/utils.test.js @@ -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() diff --git a/test/utils/mock-log.js b/test/utils/mock-log.js index ffed3743c4..32f8d367ab 100644 --- a/test/utils/mock-log.js +++ b/test/utils/mock-log.js @@ -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() } })