简体   繁体   English

如果 NPM 中不存在此库,如何在我的 Node.JS 项目中使用外部 JS 库方法

[英]How to use external JS library methods in my Node.JS project if this library does not exist in NPM

I have a problem which can be easily solved by importing an external JS library into Node.js .我有一个问题,可以通过将external JS library导入Node.js轻松解决。 However, this library does not exist in NPM .但是,此库在NPM中不存在。

I found out an old solution on StackOverflow which seems to fix the problem.我在StackOverflow上找到了一个旧的解决方案,似乎可以解决这个问题。 However, it looks wierd.然而,它看起来很奇怪。

Is there a more convenient solution in 2k20 to use external JS library methods into my Node.js code?在我的Node.js代码中使用external JS library方法在 2k20 中是否有更方便的解决方案?

  • If your library have a package.json : You can install the package directly from the git repository, for example npm install https://github.com/vendor-creator/vendor-package . If your library have a package.json : You can install the package directly from the git repository, for example npm install https://github.com/vendor-creator/vendor-package . NOTE that for this method to work, in cases where the module has to be built, the git repository should contain a dist/ folder containing the built code or have in its package.json , a prepare step responsible for building the package upon installation. NOTE that for this method to work, in cases where the module has to be built, the git repository should contain a dist/ folder containing the built code or have in its package.json , a prepare step responsible for building the package upon installation.

  • If your library does not have a package.json and is simply a vanilla JavaScript file like the Lodash JavaScript file , I would advise just like in the post you linked, to create a vendor.js file ( .min if the script is minified) , copy and paste the content of the file and require it. If your library does not have a package.json and is simply a vanilla JavaScript file like the Lodash JavaScript file , I would advise just like in the post you linked, to create a vendor.js file ( .min if the script is minified) ,复制并粘贴文件的内容并require它。 Be aware that some libraries using CDN and not NPM, are designed for browser environment and may lack CommonJS support preventing you from using require .请注意,某些使用CDN而不是 NPM 的库是为浏览器环境设计的,可能缺少CommonJS支持,从而阻止您使用require In that case you'll have to modify the library source code.在这种情况下,您将不得不修改库源代码。

    If it's a small library, there is no need to create an advanced build system.如果是小型库,则无需创建高级构建系统。 If the library is stable, just copy and paste it and you'll be fine.如果库是稳定的,只需复制并粘贴它就可以了。 When in doubt always follow the KISS principle.如有疑问,请始终遵循KISS原则。

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

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