Search code examples
javascriptwebpackecmascript-6babeljses6-modules

Unable to use MJS files on older web hosting platform


I am currently migrating a website from a new platform to a very old one. The older platform does not currently serve MJS files as the expected "application/javascript"/"application/x-javascript", and instead will serve them as an "application/octet-stream" or other invalid MIME type. I am able to change this locally within my nginx and Apache configurations, but when pushing to production I will not have access to these configurations with our hosting provider. As such, I'm searching for a simple solution for converting multiple MJS files into a compatible CJS file (or multiple CJS files) for usage on the site via standard <script> tags.

I've tried transpiling the existing set of MJS code to an ES5-compatible bundle via Webpack + Babel, but this only resulted in obscure errors; likely due to poor project setup. Additionally, I attempted to inline some of these scripts via <module>/<script type="module"> tags, but eventually gave up on this as there are multiple very large modules which all rely on each other by name.

Right now our initial MJS file is imported at the bottom of the page like so: <script type="module" src="/scripts/script.44EUR4D5.mjs"></script>

Each of the dependency scripts will all load one another by name and access exported functions or modify the DOM.

I would love to be able to replace this with something like this: <script src="/scripts/bundle.js"></script>

Wherein bundle.js is a, perhaps bundled, version of the MJS files which would be supported by most any web server handling the hosting of our app.

If the right solution for solving this issue would be to make use of a secondary project with a specialized setup (as per my note on Webpack + Babel earlier), would anyone happen to know of a simple configuration for converting the MJS files to compatible CJS?

Thanks!


Solution

  • Keep in mind that browsers only care about the Content-Type. They don’t care about the part of the URL that looks like a file extension at all.

    There’s no need to bundle the files, or convert them to CJS (which browsers don’t support anyway).

    Just rename the files to have .js file extensions. Update your import statements to match.

    You could probably automate this with any bulk renaming tool and a regex search & replace across all your source files in your IDE.