Nuxt.js: Cannot resolve '@' in serverMiddleware

Created on 27 Feb 2020  路  7Comments  路  Source: nuxt/nuxt.js

Version

v2.11.0

Reproduction link

https://codesandbox.io/s/servermiddleware-resolve-problem-hqtbw

Steps to reproduce

  1. Create server middleware
  2. import custom object from any custom js file with @ in path, that must start pointing from root of the project.

What is expected ?

@ to point to root as it does in nuxt normally.

What is actually happening?

Error: Cannot find module '@/api/routes/users'
Error: Cannot find module '@/models/user'
feature-request

Most helpful comment

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 () {...}

All 7 comments

@ 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 () {...}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

bimohxh picture bimohxh  路  3Comments

gary149 picture gary149  路  3Comments

VincentLoy picture VincentLoy  路  3Comments

danieloprado picture danieloprado  路  3Comments

jaredreich picture jaredreich  路  3Comments