javascript - webpack 的 require 是如何工作的?

标签 javascript webpack

我不明白 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/

相关文章:

javascript - 将所见即所得文本编辑器 jquery 插件与 webpack 捆绑在一起

javascript - 编写 webpack 或 babel 插件将静态属性编译到样式表中

javascript - AngularJS 模块与 CommonJS/ECMA6 模块

javascript - kinetic js HTML5 Canvas 中的 stage.toJSON()

javascript - 使用 jQuery 动态创建无序列表

javascript - 根据在 WebView React Native 中查看的当前页面注入(inject)不同的 Javascript

javascript - 如何强制 Firefox(版本 6)释放内存?

css - 如何从我的网站中删除加载了脚本标签的 css 以及该脚本标签的删除?

javascript - 无法识别 ES5 导出函数

typescript - Webpack 使用上一个构建步骤中的现有源映射