Using require
in a browser is not possible because CommonJS is designed to handle modules in non-browser environments.
To manage modules in the browser, you should follow the ECMAScript modules standard.
To use the import
and export
keywords in JavaScript files, simply add the type="module"
attribute to your script
tags.
With ECMAScript modules, you can manage modules natively without needing a build process for front-end JavaScript code.
If you need to import third-party libraries, you can:
- Include them in your static folder (packaged as either ECMAScript module or UMD) and add corresponding
script
tags
- Reference them from a CDN (packaged as either ECMAScript module or UMD) using
script
tags
- Use a build process to bundle, treeshake, and minify the entire codebase, including libraries from
node_modules
For example, here is a library available as an ECMAScript module and UMD on a CDN: