简体   繁体   English

如何使用npm发布客​​户端脚本?

[英]How to publish a client-side script using npm?

My nodejs package contains code for execution both on the backend, and a single .js file for execution on browsers. 我的nodejs程序包包含用于在后端执行的代码,以及用于在浏览器上执行的单个.js文件。 To make use of the browser script, it has to be put into a script element in an HTML file, obviously. 显然,要使用浏览器脚本,必须将其放入HTML文件中的script元素中。 My question is if there's a standard practice/convention with respect to how that browser .js file should be exposed to npm (or webpack or whatever) in a way that is independent of webpack, gulp, grunt, or other packaging tools. 我的问题是关于是否应该以独立于webpack,gulp,grunt或其他打包工具的方式将浏览器.js文件暴露给npm(或webpack或其他任何东西)是否存在标准惯例/惯例。 For example, by placing it into a scripts/ dir somewhere, or by including a simplistic nodejs/expressjs 3-line middleware that, when accessed via http://example.com/scripts/myscript.js , will send my script's content to browsers. 例如,通过将其放置在某个地方的scripts/目录中,或包括一个简单的nodejs / expressjs 3行中间件,当通过http://example.com/scripts/myscript.js访问该中间件时,会将我的脚本内容发送到浏览器。

I've found this article , but that merely explains the trivial details of how to use a script element in an HTML page, rather than how to make npm install a script in standardized asset folder for pickup by static serving routes, asset management tools, or similar. 我已经找到了这篇文章 ,但这只是解释了如何在HTML页面中使用script元素的琐碎细节,而不是如何使npm在标准化资产文件夹中安装脚本以供静态投放路线,资产管理工具,或类似。

If you are publishing your package on NPM, an alternative that could work in your situation could be by using https://unpkg.com/ CDN. 如果要在NPM上发布软件包,则可以使用https://unpkg.com/ CDN来解决您的问题。 All packages that are published on NPM are available via this CDN. 可通过此CDN获得在NPM上发布的所有软件包。

Then in your frontend code you could simply reference that single js file you need. 然后,在您的前端代码中,您可以简单地引用所需的单个js文件。

  <script src="https://unpkg.com/yourpackage/path/to/your/file.js"></script>

CDN is your best bet if you are not packing the web content in the same package. 如果您不将Web内容打包在同一包中,则CDN是最好的选择。 If your web contents are in the same package you could use 如果您的网站内容位于同一包中,则可以使用

"scripts": {
    "prepublish": "cp <source_path_of_file.js> <destination_dir>"
}

in package.json to pack it as a part of your npm package. 在package.json中将其打包为npm软件包的一部分。

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

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