简体   繁体   中英

What is the Node.js equivalent of a PHP include?

我正在寻找一种不需要常规框架的常规HTML和CSS(用于重复的组件,例如页眉,页脚,导航等)的服务器端简单解决方案。

You're looking for the

require()

function. Check out the documentation for this and other Node.js things here

If you want to use newer import statement, you may do so; it's not yet fully implemented in Node, but you can use it by using the .mjs extension on the file you need to import and then using the following command:

node --experimental-modules someFile.mjs

You can use require to require multiple files. However, since node caches the files, you will need to delete them from the cache if you want to used an un-cached version of the file.

index.js

app.get('/path', (req, res) => {
  clear()
  let headers1 = require('/headers/a.js')
  let headers2 = require('/headers/b.js')
  res.set(headers1)
  res.set(headers2)
})

// Remove from require cache
function clear() {
  delete require.cache[require.resolve('/headers/a.js')]
  delete require.cache[require.resolve('/headers/b.js')]
}

headers/a.js

module.exports = {
  'Content-Type': 'application/json'
}

headers/b.js

module.exports = {
  'Custom-Header': 'Brass Monkey'
}

I think you like require "view components". Exists multiple view engines for nodejs, for example pug , or ejs . In this case, you use include

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