简体   繁体   中英

Include a node module through express.static

So I have a node server running on localhost:3002. This server is serving some static html and plain JavaScript content. I am accessing this content through an iFrame on a Vue.js application.

My question is when I use app.use(express.static('./game')); Can I include a node module along with this action?

My reasoning for this is, within one of the plain JavaScript files of the static content, I want to use require() and obviously this does not work.

I know that I could access the module I want directly from the plain JavaScript file using a <script> tag, but I don't really want to send this to the client side directly.

Is it possible to have something that looks like this? app.use(express.static('./game'), express.static('/node_modules/jsonwebtoken'); as an example.

Yes you can, but it is not highly recommended. You could solve it as follows.

app.use(express.static(path.resolve(__dirname, './game')))
app.use(express.static(path.resolve(__dirname, '../node_modules/jsonwebtoken')))

The ideal would be to implement different logic for each area, back-end ~ front-end. This in the given case that you are developing a client-side.

Now if you are developing a server-side, the logic already changes, since the server directly renders the view internally.

Another important point to highlight is that depending on both the back-end and the front-end of the same resource, it can lead to breaking the code, on one side or the other. For a simple update of said resource.

I hope that it clarifies you to the doubt. Some doubt comment it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM