In my experience with a JavaScript-based Nuxt project, the server entry is located in server/index.js
. Here is the default code for Express.js:
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const {
host = process.env.HOST || '127.0.0.1',
port = process.env.PORT || 3000
} = nuxt.options.server
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()
To run the server script with standard Nuxt building, you need to replace the dev
script with:
"cross-env NODE_ENV=development nodemon server/index.js --watch server",
If you want to write server/index
in TypeScript for a Nuxt TypeScript project, simply renaming server/index.js
to server/index.ts
won't be enough. Nuxt needs to know that the source code is written in TypeScript and must compile it.
Nuxt handles the Webpack configuration for us by stating "I'll take care of the Webpack config, just define the settings in nuxt.config.js". But how do we make Nuxt compile the server.ts
now?
More Specifics
Let's say we have an index.ts
file in the server
subdirectory with content console.log("ok!)
. How can we:
- compile it to JavaScript,
- start the server and see "ok!" output in the terminal?
It's straightforward with Webpack, but in a TypeScript Nuxt project where direct webpack configuration is not available, it requires a different approach.