Express how to use Import / require() in Static Folder

Viewed 483

I've been trying to do this for quite some time now, does anyone know how do I use import or require in express static folder. I get require not defined and I get it its non existent in browsers and I'm too lazy to try and set up webpack/babel/browserify, is that the only way to do it and what is the fastest way?

1 Answers

You won't be able to use require in a browser because this is CommonJS and its goal is precisely to manage modules in a non-browser environment.

The browser compliant way to manage modules is the ECMAScript modules standard.

Just add the type="module" attribute on the script tags and you'll be able to use the import and export keywords in the JavaScript files.

With ECMAScript modules, you leverage a module management system that is native, and doesn't require a build process for the front-end JavaScript code.

If your question is about importing third party libraries, either:

  • Copy them into your static folder (packaged as ECMAScript module or UMD) and add the corresponding script tags
  • Reference them from some CDN (packaged as ECMAScript module or UMD) with script tags
  • Use a build process to bundle/treeshake/minify the whole code, including the libraries from node_modules

For reference, here is a library packaged as an ECMAScript module and UMD as well on a CDN: https://cdnjs.com/libraries/three.js

Related