使用 NPM jQuery 模块

NPM 是 node.js 包的一部分。本教程演示了安装和使用 npm jQuery 模块。

使用 NPM jQuery 模块

使用 NPM 安装 Node.js

要首先使用 npm jQuery 模块,我们需要安装 node.js 包中包含的 npm 模块。转到此链接并下载你的安装程序。

使用 NPM jQuery 模块

下载安装程序后,下一步是运行安装程序。

使用 NPM jQuery 模块

运行安装程序后,按下一步并接受协议;之后,按下一步三次。

使用 NPM jQuery 模块

检查选项自动安装必要的工具,单击下一步,然后单击安装

使用 NPM jQuery 模块

安装完成后,单击 Finish,然后安装带有 npm 的 Node.js。

通过命令提示符或 PowerShell 验证安装。运行以下命令。

npm -v

使用 NPM jQuery 模块

一旦安装了带有 npm 的 Node.js,下一步就是使用 npm 安装 jquery 模块。

使用 NPM 安装 jquery

确保安装模块 jquery,而不是 jQuery。请按照以下步骤操作。

第 1 步:在命令提示符下使用以下命令创建 package.json 文件,以跟踪依赖项和模块。

npm init -y

上述命令的输出将是这样的:

C:\>npm init -y
Wrote to C:\package.json:
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

第 2 步:安装 jquery 模块;使用以下命令。

npm install jquery

第三步:安装好 jquery 模块后,下一步就是安装 jsdom,因为 jQuery 是一个前端库;这就是为什么它需要一个用于后端操作的窗口。使用以下命令安装 jsdom

npm install jsdom

第 4 步:在 JavaScript 中导入 jsdom 模块。

const dom = new jsdom.JSDOM("")

第 5 步:使用 HTML 代码作为参数创建由 JSDOM 对象创建的新 jsdom 窗口。请参见下面的示例。

const dom = new jsdom.JSDOM("")

第 6 步:现在导入 jquery 并为其提供一个窗口。使用以下代码。

const jquery = require('jquery')(dom.window)

现在让我们尝试一个将 jquery 与 npm 一起使用的示例。参见示例:

// Import the jsdom module
const jsdom = require("jsdom");
// Create a window with a document
const dom = new jsdom.JSDOM(`<!DOCTYPE html>
<body>
<h2> DELFTSTACK </h2>
<p>This is delftstack.com</p>
</body>
`);
// Import the jquery with window
const jquery = require("jquery")(dom.window);
// Append a HTML element to the body
jquery("body").append("<p> The Best Tutorial Site </p>");
// Get the content of the body
const Body_Content = dom.window.document.querySelector("body");
// Print the content of body
console.log(Body_Content.textContent);

上面的代码将使用 npm jquery 将一些 HTML 内容附加到正文中。见输出:

使用 NPM jQuery 模块