What does resolve.extensions do in Webpack?

为君一笑 提交于 2021-01-26 17:56:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/40565361/what-does-resolve-extensions-do-in-webpack

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!