Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs how to serve node_modules directory to front end for access?

Tags:

Without using any packaging software such as Browserify or Webpack, I have a simple server that in nodejs.

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
app.use(bodyParser());
app.use(express.static('public'));
app.use(express.static('node_modules'));


app.post('/api/searchjob', function (req, res) {
  res.json({data: "hello"});
});

app.get('/', function(req,res) {
  res.sendfile('public/index.html');
});

app.get('/*', function(req, res){
  res.redirect('/');
})

app.listen(process.env.PORT || 3000, function () {
  console.log('Example app listening on port 3000!')
});

I want the front end to also have access to some node_modules packages, what can i do? my index.html file is in "public" directory, the folder structure look like this:

├── README.md
├── index.js
├── node_modules
├── package.json
├── public
└── yarn.lock

I tried simply put the script tag in index.html, but doesn't work <script src="../node_modules/vue2-google-maps/dist/vue-google-maps.js"></script>

like image 842
WABBIT0111 Avatar asked Apr 01 '17 03:04

WABBIT0111


People also ask

Is it mandatory to commit the node_modules folder in your application?

Usually, no. Allow npm to resolve dependencies for your packages.

How do you access a node JS module?

In order to use Node. js core or NPM modules, you first need to import it using require() function as shown below. var module = require('module_name'); As per above syntax, specify the module name in the require() function.


1 Answers

You are already using the express static middleware to serve files from your node_modules directory, so a path like this should work:

<script src="/vue2-google-maps/dist/vue-google-maps.js"></script>
like image 97
Patrick Hund Avatar answered Sep 23 '22 11:09

Patrick Hund