简体   繁体   中英

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. 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.

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.

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.

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>

CDN is your best bet if you are not packing the web content in the same package. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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