Reputation:
I have a javascript file with more than 200 lines of code for front end logic like what happens when someone clicks on button, image, etc. like a game.
I am not able to figure this out. How to link/ include, tell expressjs to use that file for front end logic and not just rely on .ejs files ?
I am not asking for module.exports to export particular parts from file. I want the whole file to be exported.
Please help.
Upvotes: 0
Views: 1512
Reputation: 97
You could also change your <script>
lines in your file to point towards a path like follows:
<script src="/filejs"></script>
Then in your app.js
add another endpoint called /filejs
with the following code:
app.get('/filejs', function(req, res) {
res.sendFile(__dirname + '/folder/file.js') //change this to your file path
})
Upvotes: 0
Reputation: 447
First you should tell express where your static file is located:
app.use(express.static(path.join(__dirname, 'yourFolder')));
Then in your route where you are rendering view you can do something like this:
return res.render("yourView",{
param1: param1,
scripts: [
'javascripts/yourFile.js'
]
});
'scripts' array is not accessible inside ejs file. In footer.ejs you can do:
<% if ( typeof scripts !== 'undefined') { %>
<% scripts.forEach(function(script){ %>
<script src="/<%- script %>"></script>
<% }); %>
<% } %>
Upvotes: 1