Alexandr Lukovnikov
Alexandr Lukovnikov

Reputation: 180

Dirname in Nuxt

I am trying to read files in a directory but cannot because __dirname is undefined

nuxt.config.js

export default {
  router: {
    middleware: ['database']
  },
  build: {
    extend: function (config, __ctx) {
      config.node = {
        fs: "empty",
        module: "empty",
        net: "empty",
      };
    },
  },
}

What can be done to determine __dirname?

Upvotes: 0

Views: 2248

Answers (1)

papa zulu
papa zulu

Reputation: 317

As far as I figured it out, Webpack always sets the __dirname to '/'. But probably not on server side. Maybe this reference will help you resolve your issue: https://codeburst.io/use-webpack-with-dirname-correctly-4cad3b265a92

You didn't say much what you are trying to accomplish, but I will wrote down a solution for one of the most common issues which usually result in people trying to use __dirname constant. Maybe it will also help you ;)

Whenever I tried to use __dirname in Nuxt, it was because I had to make a workaround for the missing require.context functionality in server side process (SSR). Doing some workarounds with require and __dirname usually caused even more issues. The best solution if you are struggling with missing require.context in Nuxt server side process is to use Plugins. They can use require.context function and are available both on server side and on client side.

Overall, I think that you should try and find your files with webpack's context functionality and avoid using __dirname.

const files = require.context('~/', true, /\/your-file-name\/.*\.ts$/)
files.keys().map(key => {
   // This is an example how to access your file's default export.
   // You will probably have to amend it to make any use of it ;)
   const file = files(key).default
})

Upvotes: 1

Related Questions