mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-11 08:33:53 +00:00
fix(cli): throw error with proper code for failed imports (#5478)
This commit is contained in:
parent
dc14200bbf
commit
e88e998d70
@ -1,28 +1,25 @@
|
||||
import path from 'path'
|
||||
import consola from 'consola'
|
||||
|
||||
const localNodeModules = path.resolve(process.cwd(), 'node_modules')
|
||||
|
||||
// Prefer importing modules from local node_modules (for NPX and global bin)
|
||||
async function _import(modulePath) {
|
||||
let m
|
||||
for (const mp of [ path.resolve(localNodeModules, modulePath), modulePath ]) {
|
||||
for (const mp of [
|
||||
path.resolve(localNodeModules, modulePath),
|
||||
modulePath
|
||||
]) {
|
||||
try {
|
||||
m = await import(mp)
|
||||
return await import(mp)
|
||||
} catch (e) {
|
||||
if (e.code !== 'MODULE_NOT_FOUND') {
|
||||
throw e
|
||||
} else if (mp === modulePath) {
|
||||
consola.fatal(
|
||||
`Module ${modulePath} not found.\n\n`,
|
||||
`Please install missing dependency:\n\n`,
|
||||
`Using npm: npm i ${modulePath}\n\n`,
|
||||
`Using yarn: yarn add ${modulePath}`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return m
|
||||
|
||||
const error = new Error(`Cannot import module '${modulePath}'`)
|
||||
error.code = 'MODULE_NOT_FOUND'
|
||||
throw error
|
||||
}
|
||||
|
||||
export const builder = () => _import('@nuxt/builder')
|
||||
|
@ -1,4 +1,3 @@
|
||||
import consola from 'consola'
|
||||
import { importModule } from '../../src/imports'
|
||||
|
||||
describe('imports', () => {
|
||||
@ -8,15 +7,11 @@ describe('imports', () => {
|
||||
test('should import core module', async () => {
|
||||
await expect(importModule('path')).resolves.toBeDefined()
|
||||
})
|
||||
test('should print error when module not found', async () => {
|
||||
await expect(importModule('not-found-module')).resolves.toBeUndefined()
|
||||
expect(consola.fatal).toHaveBeenCalled()
|
||||
expect(consola.fatal).toHaveBeenCalledWith(
|
||||
`Module not-found-module not found.\n\n`,
|
||||
`Please install missing dependency:\n\n`,
|
||||
`Using npm: npm i not-found-module\n\n`,
|
||||
`Using yarn: yarn add not-found-module`
|
||||
)
|
||||
test('should throw error with proper code when module not found', async () => {
|
||||
await expect(importModule('not-found-module')).rejects.toMatchObject({
|
||||
message: `Cannot import module 'not-found-module'`,
|
||||
code: 'MODULE_NOT_FOUND'
|
||||
})
|
||||
})
|
||||
test('should throw error when error is not module not found', async () => {
|
||||
await expect(importModule('jest/README.md')).rejects.toThrow()
|
||||
|
Loading…
Reference in New Issue
Block a user