我不明白 webpack 的 require
函数是如何工作的。例如,我正在阅读 this article关于 webpack 有如下例子:
Let's start by creating our project and installing Webpack, we'll also pull in jQuery to demonstrate some things later on.
$ npm init
$ npm install jquery --save
$ npm install webpack --save-dev
Now let's create our app's entry point, in plain ES5 for now:
src/index.js
var $ = require('jquery');
$('body').html('Hello');
And let's create our Webpack configuration, in a webpack.config.js file. Webpack configuration is just Javascript, and needs to export an object:
webpack.config.js
module.exports = {
entry: './src',
output: {
path: 'builds',
filename: 'bundle.js',
},
};
webpack如何知道require('jquery')
中的jquery是什么?我没有看到任何指定的与 jquery 相关的配置选项。
最佳答案
在这种情况下,它将像 CommonJS require
(例如,Node require
)一样工作。 (Webpack 的 require
比传统的 require
支持更多的灵 active ,但默认行为是相同的。)
This Modules section in the docs解释了 Node 如何确定从调用 require()
返回的内容。如果您需要“jquery”,它首先查找该名称的 native 模块,没有找到,然后查找 node_modules
(因为没有 /
或 ./
在路径的开头)。由于“jquery”是一个文件夹,它查看 package.json
文件以查看它声明包的 main
文件是什么,这就是它执行的内容。
整本书值得一读;例如,缓存部分很重要。
关于javascript - webpack 的 require 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35625593/