Thursday, February 16, 2017

Webpack: Throw error on missing member import

Leave a Comment

I have an import something like this:

import { foo } from 'bar'; 

Is there a way to get Webpack to throw an error if foo is not defined?

Note that I'm using Babel if that makes a difference.

2 Answers

Answers 1

It is possible to configure webpack 2 to throw an error when an import fails by using output.strictModuleExceptionHandling. The functionality was added by this pull request https://github.com/webpack/webpack/pull/3302 but it has not been documented yet. Here's how to use it:

module.exports = {     entry: {         main: "./main.js",     },     output: {         filename: "[name].bundle.js",         strictModuleExceptionHandling: true     } } 

Now if I try to import from a file which dosn't exist, or I make an import which resolves to undefined I would get error and warning messages in the webpack console:

WARNING in ./js/pedigree.js 32:35-49 "export 'default' (imported as 'DisorderLegend') was not found in './disorderLegend'  ERROR in ./js/pedigree.js Module not found: Error: Can't resolve './OkCancelDialogue' in '/home/tim/workspace/projects/public/js/ext-lib/panogram/js'  @ ./js/pedigree.js 5:0-54  @ ./js/viewerPedigree.js  @ ./main.js  @ multi (webpack)-dev-server/client?http://localhost:8080 ./main.js webpack: Failed to compile. 

In the chrome console you'll get a warning like this:

warning message in chrome

Answers 2

Firstly enable WARNING of missing modules by enabling modules

module: {   rules: [     {       test: /\.js$/,       exclude: /node_modules/,       loader: 'babel-loader',       options: {          presets: [            [ 'es2015', { modules: false } ] // important modules: false          ]       }     }   ] } 

Now in your console you should see something like this: enter image description here

Next convert this warning to error and exit webpack build with error.

plugins: [   function () {     const isModuleDependencyWarning = warn => warn.name === 'ModuleDependencyWarning';     const printError = warn => console.error('\x1b[31m', warn.message, '\x1b[0m');     this.plugin('done', function(stats) {       const missingModules = stats.compilation.warnings.filter(isModuleDependencyWarning);       if (missingModules.length) {         missingModules.forEach(printError);         process.exit(1);       }     });   } ] 

This should break webpack build with error on ModuleDependencyWarning: enter image description here

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment