Warm tip: This article is reproduced from stackoverflow.com, please click
javascript node.js three.js

Importing Three.js Module in a Node express server

发布于 2020-04-16 12:31:14

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.

Questioner
Isaac Dalli
Viewed
60
Lonnie Best 2020-02-04 20:24

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.