I am trying to import threeJs module inside my html script to test out, I have it working when I download the three.js file and have a link to it. But trying to change to modules is giving me trouble. I have the following code to import the Three.js module.
<html lang="en">
<head>
<title>ThreeJs Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="css/main.css">
</head>
<body>
<script type="module">
import * as THREE from '/node_modules/three/build/three.module.js';
</script>
</body>
</html>
I have the following error when doing so: Error
I have the following file structure: file structure
in the node server i'm routing to a js file which has the following code:
const path = require('path');
const router = express.Router();
const fileDir = path.join(__dirname, '../../pages/threeTest');
router.use('/', express.static(fileDir));
router.get('/', (req, res) => {
res.sendFile(fileDir+'/html/index.html')
});
module.exports = router;
I have the routing and server working just fine but cant manage to get it working when the html/js file needs to import a module from the client side. It wont be surprising if its a simple fix or im doing something stupid. Sorry if so.
You have to move the three.module.js
file to a location that Express will serve. For example, if you have a public folder where you have other static files that are being served by Express, put the three.module.js
file there and then put the correct URL to that resource in the import statement that's in your html's script.
In other words, the web browser doesn't have access to /node_modules/three/build/three.module.js
. Those are server-side files that Express hides from the web browser by default.
To be able to use other files from the three folder such as loaders, lights so on do I need to move the whole three folder inside node_modules or will the three.modules.js file will be enough?
Its easy to get this mixed up. You have to understand that the html file is being read by the web browser and the web browser only has access to files being served by the web server (Express). Files in the
node_modules
folder are not served by Express. If you want a js file to be accessible by the web browser, you'll have to create a folder within your Express project that is public and put the js file inside of that folder. Then modify your import's url to point to that resource. Here's a link explaining how to serve files.Perfect, it seems to do the trick. I should have knew this by now. Thanks for the answer and quick response.