Fix Webpack's ability to package an app using the mime module

By: (plus.google.com) +David Herron; Date: August 2, 2018

Tags: Node.JS » Webpack

Application development with Vue.js, Electron, and other frameworks, requires using Webpack. Being a Webpack newbie I'm not sure what it does, but it is required for the tasks I'm doing right now. One of which failed with a strange error message while trying to build a Vue.js component which used the mime module. Namely, we have to instruct Webpack to recognize the JSON files included in the mime module.

The situation is - I'm developing a Vue.js component that I'm hoping to distribute as an npm package. I've duplicated the build process from another Vue.js component, added my component code, and hoped to have it quickly building.

However, the build fails with:

ERROR in ./node_modules/mime/index.js
Module not found: Error: Can't resolve './types/other' in '/Volumes/Extra/akasha-tools/vue-file-tree/node_modules/mime'
 @ ./node_modules/mime/index.js 4:55-79
 @ ./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/vue-file-tree.vue
 @ ./src/vue-file-tree.vue

ERROR in ./node_modules/mime/index.js
Module not found: Error: Can't resolve './types/standard' in '/Volumes/Extra/akasha-tools/vue-file-tree/node_modules/mime'
 @ ./node_modules/mime/index.js 4:26-53
 @ ./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/vue-file-tree.vue
 @ ./src/vue-file-tree.vue

These references to types/other and types/standard are due to how the mime module is implemented. The entirety of the module is:

var Mime = require('./Mime');
module.exports = new Mime(require('./types/standard'), require('./types/other'));

It is the mime module which require's those two modules. Inside the module's folder hierarchy are two files:

$ ls node_modules/mime/types
other.json	standard.json

You may or may not know this - but Node.js can require("path/to/fileName.json") and automagically read in the JSON file. That's what the mime module is doing. And because Node.js also allows you to drop off the file extension, the author of the mime module has dropped off the .json extension, and it all works fine for him.

He even said so in the corresponding bug report: (github.com) https://github.com/broofa/node-mime/issues/172

The fix is very simple. Webpack has a configuration setting allowing Webpack to recognize additional file extensions that can be used in the require statement. Simply change your Webpack configuration to use this:

resolve: {
    extensions: [ '.js' , '.json' ],
    ...
},

That is - add '.json' to the array of allowed file extensions. Very simple.

« Fix Webpack's ability to load CSS while packaging an app A file-system browser component for Electron/Vue.js applications »