NUXT: Module not found: Error: Can't resolve 'fs'

15,832

You can't use NodeJs specific module on browser.

To solve your issue, you can create an API using Nuxt server middleware. The code below, inspired by https://github.com/nuxt-community/express-template.

  1. Create a file, index.js in api/index.js. Then fill it with:

    const express = require('express')
    
    // Create express instance
    const app = express()
    
    // Require API routes
    const carousel = require('./routes/carousel')
    
    // Import API Routes
    app.use(carousel)
    
    // Export the server middleware
    module.exports = {
      path: '/api',
      handler: app
    }
    
  2. Create carousel.js in api/routes/carousel.js. Then fill it with:

    const { Router } = require('express')
    const glob = require('glob')
    
    const router = Router()
    
    router.get('/carousel/images', async function (req, res) {
      const options = {
        cwd: './static'
      }
      const filenames = glob.sync('*', options)
    
      let items = [];
      filenames.forEach(filename =>
        items.push({
          'src': '/'+filename
        })
      );
    
      return res.json({ data: items })
    })
    
    module.exports = router
    
  3. Register your server middleware in nuxt.config.js

    module.exports = {
      build: {
        ...
      },
      serverMiddleware: [
        '~/api/index.js'
      ]
    }
    
  4. Call the api in your page / component. I assume you're using Axios here (axios-module).

    <script>
    export default {
      async asyncData ({ $axios }) {
        const images = (await $axios.$get('/api/carousel/images')).data
    
        return { images }
      }
    }
    </script>
    
Share:
15,832
user1592380
Author by

user1592380

Updated on June 04, 2022

Comments

  • user1592380
    user1592380 almost 2 years

    I'm starting out with vue and nuxt, I have a project using vuetify and I'm trying to modify the carousel component to dynamically load images from the static folder. So far I've come up with:

        <template>
        <v-carousel>
            <v-carousel-item v-for="(item,i) in items" :key="i" :src="item.src"></v-carousel-item>
        </v-carousel>
        </template>
    
    
        <script>
        function getImagePaths() {
            var glob = require("glob");
            var options = {
            cwd: "./static"
            };
            var fileNames = glob.sync("*", options);
            var items = [];
            fileNames.forEach(fileName =>
            items.push({
                'src': '/'+fileName
            })
            );
            return items;
        }
        export default {
            data() {
            return {items :getImagePaths()};
            }
        };
    
        </script>
    

    When I test this I see:

    ERROR in ./node_modules/fs.realpath/index.js
    Module not found: Error: Can't resolve 'fs' in '....\node_modules\fs.realpath'
    ERROR in ./node_modules/fs.realpath/old.js
    Module not found: Error: Can't resolve 'fs' in ....\node_modules\fs.realpath'
    ERROR in ./node_modules/glob/glob.js
    Module not found: Error: Can't resolve 'fs' in '....\node_modules\glob'
    ERROR in ./node_modules/glob/sync.js
    Module not found: Error: Can't resolve 'fs' in '.....\node_modules\glob'
    

    googling this I see a bunch of references like https://github.com/webpack-contrib/css-loader/issues/447.

    These suggest that you have to midify the webpack config file with something like:

    node: {
      fs: 'empty'
    }
    

    I know very little about webpack. I found https://nuxtjs.org/faq/extend-webpack/ , but am not sure how to modify the webpack config file in this case.

    How do I do this?

  • Stefan Shi
    Stefan Shi almost 5 years
    Thank you very much for the detailed exemplary code. Based on this code and the express-template, I managed to load image from specific directory in a dynamic page based on the route name. However, I found that such custom API won't work for static generated site using nuxt generate. If I understand correctly, this is because there simply won't be any server we can call our API from. I am wondering is there any workaround for this? Is it possible to use custom API like shown here for static site?
  • Moiz Sohail
    Moiz Sohail about 2 years
    you're a genius