From e88e998d70c2e195faa0b4273bbc28a85c49e078 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Sun, 7 Apr 2019 14:55:53 +0430 Subject: [PATCH] fix(cli): throw error with proper code for failed imports (#5478) --- packages/cli/src/imports.js | 21 +++++++++------------ packages/cli/test/unit/imports.test.js | 15 +++++---------- 2 files changed, 14 insertions(+), 22 deletions(-) diff --git a/packages/cli/src/imports.js b/packages/cli/src/imports.js index b68f1bc38c..22f1bee6ec 100644 --- a/packages/cli/src/imports.js +++ b/packages/cli/src/imports.js @@ -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') diff --git a/packages/cli/test/unit/imports.test.js b/packages/cli/test/unit/imports.test.js index 75f040f0c4..93e5e361b8 100644 --- a/packages/cli/test/unit/imports.test.js +++ b/packages/cli/test/unit/imports.test.js @@ -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()