Hey all, I’m using npm to add BabylonJS to my NodeJS / Express project and am having trouble importing the package into my main javascript file. I’m fairly new to web dev so perhaps the solution is something simple I’m missing. The steps I’ve taken are:
1. I used express-generator to quickly create a NodeJS / express skeleton without a specialized view renderer.
npx express-generator --no-view
2. To add BabylonJS to the project I execute:
npm install @babylonjs/core --save
3. At the top of my javascript project file I import BabylonJS using:
import * as BABYLON from ‘@babylonjs/core/Legacy/legacy’;
4. I run the NodeJS server:
npm start
5. When I access the page at localhost:3000, the console displays the following error:
Cannot use import statement outside a module
After searching for solutions online, I found that potentially adding “type”: “module” to package.lock could help resolve this issue, but when doing so an error is thrown when I attempt to start the server, leading me to believe that this causes other parts of the project to break.
Also your error suggest that you are not using a transpiler and our ES6 packages contain ES6 import statement not compatible with all version of nodes and usually not with .js extensions. So you would need to use babel or such to transpile imports statements to require.
The easiest in your case as you seem to be willing to use all of Babylon might be to use the UMD package npm install babylonjs
Thank you for your help with this. No luck with replacing BABYLON with another variable name, however I have revisited installing the babylonjs package. One of the reasons I looked at using @babylonjs/core previously was because of the following error I receive when trying npm install babylonjs.
Right now, when I run npm install babylonjs the following errors occur:
Sounds great, I decided to use the preview version in the meanwhile, although I do still encounter the “Cannot use import statement outside a module” error when trying to use the imported package.
As @sebavan suggested, this may be resolved with the support of a transpiler, however my understanding is that node version (v14.15.1) should have support for ES6 import statements. Is there a step I missing between the following actions to get things going?
1. Add BabylonJS to the project with npm:
npm install babylonjs@preview --save
2. Add an import statement to the main javascript project file:
import * as BABYLON from ‘babylonjs’;
3. Run the NodeJS server:
npm start
4. After visiting the page at localhost:3000, the console continues to display the error:
Cannot use import statement outside a module
From what @sebavan suggested earlier, it looks like the solution to this would be to use a compiler. In the end, I decided to use the cdn version of BabylonJS and things are working great! thank you for your support!