As part of a project that dates back several years, I am currently revamping the ScriptManager class. Previously, the code would retrieve scripts from a database with variations depending on the customer and installation, where the application used Chrome Embedded Framework to showcase web pages. The existing approach involved reading custom JavaScript code and using eval() which is considered highly undesirable.
To address this, I am replacing the old code with a more flexible ScriptManager class. This new implementation can accommodate dynamically inserted code and has the ability to load code as modules utilizing JavaScript's dynamic import() command or loading them as pure scripts by creating script tags in the document.
One challenge I'm facing is the presence of numerous diverse custom code blocks in the database. Not all of these are modules; some remain pure scripts until they are converted into modules later on. While my new code can manage this situation as described, I am still looking for a way to determine whether the script code retrieved from the database is a module. This will allow me to choose between using the import() command or inserting a script tag accordingly.
My temporary solution involves ensuring that any module script code includes "export const isModule = true" and then checking for this after calling import(). Although this method works, it results in a module variable for pure script code as well, albeit one without any exports. Ideally, I'd prefer not to rely on developers remembering to add isModule = true to future modules they develop.
Is there a simpler way to detect if code is a module without resorting to complex analysis to check for exports? Since import() returns an object without throwing errors even when there are no exports present, I am unsure how to identify this scenario.
UPDATE: To illustrate the intended functionality, consider the following pseudo code snippets:
// Hypothetical code snippet fetching a script string.
let code = getSomeCodeFromTheDatabase();
// Save the code for later retrieval.
let filename = 'some-filename.js';
saveCodeToFile(code, filename);
// Attempt to dynamically import the script as a module.
let module = await import(filename);
// If it is NOT a module, load it as a script tag instead.
// Here lies the necessity to differentiate between module and
// pure script code.
if (!module.isModule) {
let scriptTag = document.createElement('script');
scriptTag.src = filename;
document.head.appendChild(script);
}