diff --git a/packages/core/src/module.js b/packages/core/src/module.js index 083460d5ef..d4b5839364 100644 --- a/packages/core/src/module.js +++ b/packages/core/src/module.js @@ -143,7 +143,32 @@ export default class ModuleContainer { // Resolve handler if (!handler) { - handler = this.nuxt.resolver.requireModule(src, { useESM: true }) + try { + handler = this.nuxt.resolver.requireModule(src, { useESM: true }) + } catch (error) { + if (error.code !== 'MODULE_NOT_FOUND') { + throw error + } + + let message = 'Module `{name}` not found.' + + if (this.options.buildModules.includes(src)) { + message += ' Please ensure `{name}` is in `devDependencies` and installed. HINT: During build step, for npm/yarn, `NODE_ENV=production` or `--production` should NOT be used.'.replace('{name}', src) + } else if (this.options.modules.includes(src)) { + message += ' Please ensure `{name}` is in `dependencies` and installed.' + } + + message = message.replace(/{name}/g, src) + + if (this.options._cli) { + throw new Error(message) + } else { + // TODO: Remove in next major version + message += ' Silently ignoring module as programatic usage detected.' + consola.warn(message) + return + } + } } // Validate handler diff --git a/packages/core/test/module.test.js b/packages/core/test/module.test.js index ac47e1a2f9..42bdcaeec2 100644 --- a/packages/core/test/module.test.js +++ b/packages/core/test/module.test.js @@ -454,4 +454,25 @@ describe('core: module', () => { expect(handler).toBeCalledTimes(1) expect(module.requiredModules.moduleTest).toBeDefined() }) + + test('should prevent adding not installed buildModules', async () => { + const module = new ModuleContainer({ + resolver: { requireModule }, + options: { + ...defaultOptions, + buildModules: ['test-build-module'] + } + }) + + requireModule.mockImplementationOnce(() => { + const moduleNotFound = new Error() + moduleNotFound.code = 'MODULE_NOT_FOUND' + throw moduleNotFound + }) + + const result = await module.addModule('test-build-module', true) + + expect(result).toBeUndefined() + expect(consola.warn).toBeCalledWith('Module `test-build-module` not found. Please ensure `test-build-module` is in `devDependencies` and installed. HINT: During build step, for npm/yarn, `NODE_ENV=production` or `--production` should NOT be used. Silently ignoring module as programatic usage detected.') + }) })