I just went through the discomforting import vs. require time suck that many of us go through, trying to use both ES6 and CommonJS files in the same project, in a stand-alone Node.js utility I am working on.
I did find the the following solutions that you (hopefully) find at the end of a lengthy Web/Stack Overflow session:
- Change the extension of the main file to ".mjs"
- OR: Add
type: "module"to the project'spackage.jsonfile - Then add these two lines of alchemy to your project to get back the use of
require:
import {createRequire} from "module";
const require = createRequire(import.meta.url);
That all works. Unfortunately, I have legacy files with ".js" extensions in the project that are actually modules. They use the import statement and they also export symbols. This leads right back to that annoying "cannot use import outside a module" error when I ry to run the utility.
Is there a way to use package.json to mark those included files too as modules? I am really loathe to change their extensions to ".mjs" because they are used by a lot of projects and that would lead to fairly massive GitHub headache.
If not, is there some other way to solve this problem?
----- SOURCE CODE SNIPPETS ----
My package.json file for the utility:
{
"name": "utility",
"main": "inspect-animation-model-data-file.js",
"type": "module"
}
Here is the code that imports the problem file (FBXLoader.js), with the createRequire alchemy statements shown:
import {createRequire} from "module";
const require = createRequire(import.meta.url);
import FBXLoader from "../public/javascripts/threejs/examples/jsm/loaders/FBXLoader.js";
Here are the elements in FBXLoadder.js that trigger the "cannot use import" error.
import {
AmbientLight,
AnimationClip,
...
// And...
export { FBXLoader };