如何使用 npm 发布客户端脚本? [英] How to publish a client-side script using npm?
问题描述
我的 nodejs 包包含在后端执行的代码,以及在浏览器上执行的单个 .js 文件.显然,要使用浏览器脚本,必须将其放入 HTML 文件的 script
元素中.我的问题是,关于浏览器 .js 文件应该如何以独立于 webpack、gulp、grunt 或其他打包工具的方式暴露给 npm(或 webpack 或其他任何东西),是否存在标准实践/约定.例如,通过将其放入 scripts/
目录中的某个位置,或者通过包含一个简单的 nodejs/expressjs 3 行中间件,当通过 http://example.com/scripts/访问时myscript.js
,将我的脚本内容发送到浏览器.
My nodejs package contains code for execution both on the backend, and a single .js file for execution on browsers. To make use of the browser script, it has to be put into a script
element in an HTML file, obviously. 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. 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.
我发现 这篇文章,但这只是解释了如何在 HTML 页面中使用 script
元素的琐碎细节,而不是如何让 npm 安装脚本在标准化资产文件夹中,供静态服务路线、资产管理工具或类似工具取货.
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.
推荐答案
如果您在 NPM 上发布您的包,则可以使用 https://unpkg.com/ CDN.在 NPM 上发布的所有包都可以通过此 CDN 获得.
If you are publishing your package on NPM, an alternative that could work in your situation could be by using https://unpkg.com/ CDN. All packages that are published on NPM are available via this CDN.
然后在您的前端代码中,您可以简单地引用您需要的单个 js 文件.
Then in your frontend code you could simply reference that single js file you need.
<script src="https://unpkg.com/yourpackage/path/to/your/file.js"></script>
这篇关于如何使用 npm 发布客户端脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!