refactor: add module not found fatal message in cli/imports (#4741)

This commit is contained in:
Xin Du (Clark) 2019-01-12 20:21:43 +00:00 committed by Pooya Parsa
parent dfaffc0183
commit ef05e005a6
3 changed files with 44 additions and 5 deletions

View File

@ -1,7 +1,9 @@
<template> <template>
<div> <div>
<h1>styled-vue</h1> <h1>styled-vue</h1>
<a href="https://github.com/egoist/styled-vue" class="github">Check it out on GitHub.</a> <a href="https://github.com/egoist/styled-vue" class="github">
Check it out on GitHub.
</a>
</div> </div>
</template> </template>

View File

@ -1,14 +1,26 @@
import path from 'path' import path from 'path'
import consola from 'consola'
const localNodeModules = path.resolve(process.cwd(), 'node_modules') const localNodeModules = path.resolve(process.cwd(), 'node_modules')
// Prefer importing modules from local node_modules (for NPX and global bin) // Prefer importing modules from local node_modules (for NPX and global bin)
async function _import(modulePath) { async function _import(modulePath) {
let m let m
try { for (const mp of [ path.resolve(localNodeModules, modulePath), modulePath ]) {
m = await import(path.resolve(localNodeModules, modulePath)) try {
} catch (e) { m = await import(mp)
m = await import(modulePath) } 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 return m
} }
@ -17,3 +29,4 @@ export const builder = () => _import('@nuxt/builder')
export const webpack = () => _import('@nuxt/webpack') export const webpack = () => _import('@nuxt/webpack')
export const generator = () => _import('@nuxt/generator') export const generator = () => _import('@nuxt/generator')
export const core = () => _import('@nuxt/core') export const core = () => _import('@nuxt/core')
export const importModule = _import

View File

@ -0,0 +1,24 @@
import consola from 'consola'
import { importModule } from '../../src/imports'
describe('imports', () => {
test('should import relative module', async () => {
await expect(importModule('jest')).resolves.toBeDefined()
})
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 when error is not module not found', async () => {
await expect(importModule('jest/README.md')).rejects.toThrow()
})
})