fix(core): clear resolver cache for project files dev mode (#6490)

This commit is contained in:
Pim 2019-10-01 13:04:24 +02:00 committed by Pooya Parsa
parent 37bdf7496e
commit 49136bcd1b
4 changed files with 36 additions and 5 deletions

View File

@ -3,7 +3,12 @@ import fs from 'fs-extra'
import consola from 'consola'
import esm from 'esm'
import { startsWithRootAlias, startsWithSrcAlias } from '@nuxt/utils'
import {
startsWithRootAlias,
startsWithSrcAlias,
isExternalDependency,
clearRequireCache
} from '@nuxt/utils'
export default class Resolver {
constructor (nuxt) {
@ -138,9 +143,17 @@ export default class Resolver {
lastError = e
}
const isExternal = isExternalDependency(resolvedPath)
// in dev mode make sure to clear the require cache so after
// a dev server restart any changed file is reloaded
if (this.options.dev && !isExternal) {
clearRequireCache(resolvedPath)
}
// By default use esm only for js,mjs files outside of node_modules
if (useESM === undefined) {
useESM = /.(js|mjs)$/.test(resolvedPath) && !/node_modules/.test(resolvedPath)
useESM = !isExternal && /.(js|mjs)$/.test(resolvedPath)
}
// Try to require

View File

@ -442,7 +442,7 @@ describe('core: resolver', () => {
const resolver = new Resolver({
options: {}
})
resolver.resolvePath = jest.fn()
resolver.resolvePath = jest.fn().mockReturnValue('/var/nuxt/resolver/file.js')
resolver.esm = jest.fn()
resolver.requireModule('/var/nuxt/resolver/file.js', { esm: true })

View File

@ -1,6 +1,10 @@
export function isExternalDependency (id) {
return /[/\\]node_modules[/\\]/.test(id)
}
export function clearRequireCache (id) {
const entry = require.cache[id]
if (!entry || id.includes('node_modules')) {
if (!entry || isExternalDependency(id)) {
return
}
@ -17,7 +21,7 @@ export function clearRequireCache (id) {
export function scanRequireTree (id, files = new Set()) {
const entry = require.cache[id]
if (!entry || id.includes('node_modules') || files.has(id)) {
if (!entry || isExternalDependency(id) || files.has(id)) {
return files
}

View File

@ -0,0 +1,14 @@
import { isExternalDependency, getPKG } from '../src/cjs'
describe('util: cjs', () => {
test('isExternalDependency works', () => {
expect(isExternalDependency('/var/nuxt/node_modules/dependency.js')).toBe(true)
expect(isExternalDependency('/var/nuxt/dependency.js')).toBe(false)
expect(isExternalDependency('C:\\nuxt\\node_modules\\dependency.js')).toBe(true)
expect(isExternalDependency('C:\\nuxt\\dependency.js')).toBe(false)
})
test('getPKG should not throw error on non existing package', () => {
expect(() => getPKG('this-doesnt-existsw')).not.toThrow()
})
})