Basj
Basj

Reputation: 46393

Minimal number of commands to produce a client-side ready-to-use Javascript code?

For many JS libraries we can find on Github, it's nowadays impossible to use them directly in a client-side project by doing:

<script src="thelibrary.js"></script>

The browser won't accept the require and other Node-related keywords that are present both in fernet.js and even in fernetBrowser.js.

I have read a few tutorials here are there that suggest to install Node (with npm), then browserify or webpack and also a transpiler, etc. but before installing any new software, I usually make sure it's absolutely needed to understand well how it works.

Question: what is the minimum number of command-line commands to have to run to be able to turn a .js using require (such as fernetBrowser.js) into a .js file loadable directly in a browser on client-side?

Upvotes: 1

Views: 204

Answers (1)

Guerric P
Guerric P

Reputation: 31835

In your example, the file is ready for use in a browser environment, because it has been built with browserify in order to copy all of the libraries and map them to their path (e.g: 'crypto-js/aes'). Browserify also adds some boilerplate code that enables the browser to work with the CommonJS syntax (require and module.exports).

So to answer your question, the minimal number of commands to run, in order to create a browser-ready package from a file using CommonJS imports is one, since the only task to perform is to bundle the code and its dependencies into a single file (+ also install the dependencies):

npm i -g browserify  # once for all
npm i
browserify -s fernet fernet.js > fernetBrowser.js

Optionally, for a production-ready file, you could also use a minifier, like Terser in order to serve the smaller possible JavaScript file (and obfuscate your code at the same time).

If there are multiple JS files to bundle, here is an answer: Browserify multiple files into a single bundle

Upvotes: 1

Related Questions