Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does resolve.extensions do in Webpack?

Tags:

webpack

Here is the official document about resolve.extensions

resolve.extensions

An array of extensions that should be used to resolve modules. For example, in order to discover CoffeeScript files, your array should contain the string ".coffee".

Default: ["", ".webpack.js", ".web.js", ".js"]

IMPORTANT: Setting this option will override the default, meaning that webpack will no longer try to resolve modules using the default extensions. If you want modules that were required with their extension (e.g. require('./somefile.ext')) to be properly resolved, you must include an empty string in your array. Similarly, if you want modules that were required without extensions (e.g. require('underscore')) to be resolved to files with “.js” extensions, you must include ".js" in your array.

I am totally confused by this.

"If you want modules that were required with their extension (e.g. require('./somefile.ext')) to be properly resolved, you must include an empty string in your array."

Why?

"Similarly, if you want modules that were required without extensions (e.g. require('underscore')) to be resolved to files with “.js” extensions, you must include ".js" in your array."

Why? what if I include ".js" and ".css" in the array.

I am not clear about the behavior of resolve.extension. Please explain with example.

like image 643
Nicolas S.Xu Avatar asked Nov 12 '16 17:11

Nicolas S.Xu


People also ask

What is __ Dirname in webpack?

__dirname returns the the directory name of the current module. Let's take a look at some code that uses __dirname . Without webpack. This is what the output of it looks like.


1 Answers

Webpack uses resolve.extensions to generate all the possible paths to the module, e.g.

function getPaths(module) {
    return ['', '.js', '.css'].map(ext => module + ext);
}

getPaths('./somefile'); // ['./somefile', './somefile.js', './somefile.css']

getPaths('./somefile.js'); // ['./somefile.js', './somefile.js.js', './somefile.js.css']

Webpack would then proceed to lookup each of those paths until it finds a file.

like image 67
riscarrott Avatar answered Dec 07 '22 23:12

riscarrott