https://codesandbox.io/s/servermiddleware-resolve-problem-hqtbw
@ in path, that must start pointing from root of the project.@ to point to root as it does in nuxt normally.
Error: Cannot find module '@/api/routes/users'
Error: Cannot find module '@/models/user'
@ is a Webpack alias for the project root. Server middleware are loaded by Node, you must use relative paths.
@matteo-rigon No way to implement same in Node? It will make life easier, cause then same files can be used both in nuxt and in server middleware at the same time.
@payalord Not official way but you can try better-module-alias. I started working on a better POC aliaz but not stable.
As you may have heard, we are working on Nuxt functions which make API development much easier for nuxt :)
A detailed gist discussing different Node alias methods: https://gist.github.com/branneman/8048520
@pi0 you guys doing great job, big thanks for all of you for that. I will try to implement in serverMiddleware better-module-alias. And will check your project too. Thanks.
Duplicate of #4580
Fixed it like this:
// File: `/api/index.js` <-- my nuxt serverMiddleware
const moduleAlias = require('module-alias')
moduleAlias.addAliases({
'@' : __dirname + '/../'
})
module.exports = require('./app')
// File: `/api/app.js`
import express from 'express'
import routes from './routes'
const app = express()
// Import API Routes
app.use(routes)
// Export the server middleware
export default {
path: '/api',
handler: app
}
// File: `/api/routes.js`
import User from '@/models/user' // <-- works fine
...
// File: `/models/user.js`
export default function User () {...}
Most helpful comment
Fixed it like this: