Creating small open source tools is a passion of mine, and I strive to provide the best experience for my users. My packages usually consist of just one function, so here's what I aim to offer:
- A JavaScript file that users can easily add by including the
src
attribute in thescript
tag. This script will then allow them to call my function in their own scripts below. Ideal for those who prefer not to use a package manager:
<script src="https://amazingCDN.com/isEven.js"></script>
<script>
isEven()
</script>
- A JavaScript file that can be packaged and published for NPM users to conveniently install with
npm install isEven
, followed by importing my package.
Both JS files should derive from the same source code. Let's assume the source code contains a named function that needs to be added to the window
object and made importable when using Webpack. When packaging the files, I want only two JS output files generated. As for CDN support, let's say I utilize jsDelivr to fetch my GitHub-hosted JS file and handle minification without manual intervention.
I attempted writing my code as a module and utilizing Browserify with the standalone flag, which worked well with CommonJS modules. However, for ES modules compatibility, I had to resort to esmify, resulting in an object return with a default
key. This forced me to refer to the function as foo.default()
instead of foo()
, which is less than ideal.
Another approach involved writing it as a standalone file and executing the following:
echo 'export default ' | paste -d'\0' - src.js > module.js
While somewhat successful, I am curious about more advanced and dependable solutions available.
Any suggestions on how to accomplish this effectively?