Web-development – Correct way to serve file that’s in node_modules

node.jsnpmweb-development

Say I have this structure:

project/
  node_modules/
         xxx/
           asset.js
           index.html 
  app.js

and in app.js I have:

const express = require('express');
const app = express();

app.use('/docs', (req,res) => {
   res.render(require.resolve('./node_modules/xxx/index.html'));
});

app.listen(3000);

the problem is since the server is most likely running from the project root directory, the index.html file won't have the right path to pick up the assets.js file.

For example, in index.html if base is set like so:

<base href="/">

that won't work. I could try using:

<base href="node_modules/xxx/">

Another solution would be to bundle everything together so that the index.html file doesn't need to make any requests for static assets, but I am looking for a good solution for how make sure the path resolution works somewhat generically. For example, if the express server is not launched in the project root, but another subdir.

Best Answer

Well, I solved this with Laravel Mix:

in the webpack.mix.js

mix.copy('node_modules/cryptocurrency-icons/svg/color/', 'public/img/coins');