繁体   English   中英

通过 NPM(在 node_modules 文件夹中)安装时,引用 JavaScript 库的最佳做法是什么?

[英]What is the best practice to reference JavaScript libraries that when installed via NPM (in the node_modules folder)?

例如,我创建了文件夹,用 VS Code 打开它。 打开一个终端,使用命令npm install jquery ,它在我创建的文件夹中创建了一个文件夹 node_modules 。 然后我创建一个 HTML 文件,将 HTML 模板放入,现在我想引用 jQuery。 我知道如何在语法上引用文件以及所有这些,我只是想了解最佳实践。

我是否只是在其中引用 jQuery... JavaScript 文件? 还是我错过了一步?

在开始一个新项目之前,您应该使用npm init 这将初始化项目并生成package.json文件。 This package.json file is used for managing the project's dependencies(libraries), scripts, version etc. And after this every time you install a library using npm it will get listed in this package.json file under dependencies section.

初始化 npm 后的示例:

  npm i jquery

你可以使用它

const jquery = require('jquery')

或者

import jquery from 'jquery';

IE; 不使用相对路径,例如:

import jquery from '../../node_modules/jquery..'

听起来您缺少构建步骤。

使用 npm 进行开发时,通常使用带有编译器、捆绑器和压缩器的工具链,它们从node_modules文件夹中读取库并将资源放入实际部署的build文件夹中,并从该文件夹中加载 js 文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM