Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

require is not defined #12797

Closed
pixelpaulaus opened this issue Nov 16, 2021 · 38 comments
Closed

require is not defined #12797

pixelpaulaus opened this issue Nov 16, 2021 · 38 comments

Comments

@pixelpaulaus
Copy link

Environment

latest versions

Reproduction

<img :src="require('~/assets/image.png')"> anywhere in vue component.

Describe the bug

require is not defined when using it such as....

<img :src="require('~/assets/image.png')">

Additional context

No response

Logs

at $id_9513b4f8 (file://./.nuxt/dist/server/server.mjs:10135:22)
at __instantiateModule__ (file://./.nuxt/dist/server/server.mjs:10596:9)
at __ssrLoadModule__ (file://./.nuxt/dist/server/server.mjs:10543:25)
at ssrImport (file://./.nuxt/dist/server/server.mjs:10568:13)
at $id_45a9f067 (file://./.nuxt/dist/server/server.mjs:9928:37)
at __instantiateModule__ (file://./.nuxt/dist/server/server.mjs:10596:9)
at __ssrLoadModule__ (file://./.nuxt/dist/server/server.mjs:10543:25)
at ssrImport (file://./.nuxt/dist/server/server.mjs:10568:13)
at $id_7689e89d (file://./.nuxt/dist/server/server.mjs:1935:37)
at async __instantiateModule__ (file://./.nuxt/dist/server/server.mjs:10596:3)
@danielroe
Copy link
Member

If you are using vite then require will not work; it's webpack-only. Instead, just use:

<template>
  <div class="app">
    <img src="~/assets/image.png">
  </div>
</template>

@pixelpaulaus
Copy link
Author

pixelpaulaus commented Nov 16, 2021

okay, so i have found that it is using vite by default. Strange as i did not set that. So i assume nuxt3 uses Vite by default? I cant see anywhere in the docs to make it use webpack over vite.

@danielroe
Copy link
Member

@pixelpaulaus You can set vite: false in your nuxt.config.

@kayoderock
Copy link

Yeah @pixelpaulaus, I had this same issue, how can I make a dynamic src using Vite?

@kayoderock
Copy link

Yeah found it https://vitejs.dev/guide/assets.html#new-url-url-import-meta-url - Vite docs

imgUrl () {
    return new URL(`../assets/${this.icon}.svg`, import.meta.url).href
  }

@tsulatsitamim
Copy link

Yeah found it https://vitejs.dev/guide/assets.html#new-url-url-import-meta-url - Vite docs

imgUrl () {
    return new URL(`../assets/${this.icon}.svg`, import.meta.url).href
  }

not work in ssr

@androot-dev
Copy link

Alguna solución a este problema, para ssr ?

@prstwo
Copy link

prstwo commented Apr 9, 2022

Yeah found it https://vitejs.dev/guide/assets.html#new-url-url-import-meta-url - Vite docs

imgUrl () {
    return new URL(`../assets/${this.icon}.svg`, import.meta.url).href
  }

according to this page: https://vitejs.dev/guide/assets.html#new-url-url-import-meta-url:::

Does not work with SSR

This pattern does not work if you are using Vite for Server-Side Rendering, because import.meta.url have different semantics in browsers vs. Node.js. The server bundle also cannot determine the client host URL ahead of time.

@spot-mathis
Copy link

any solutions for this?

@juancarlos-ctg
Copy link

juancarlos-ctg commented May 5, 2022

if you're using nuxt 3 just put the img src as "assets/<whatever path to your img>".

By default nuxt 3 will not use the @ for specifying the path in the Vue.js

So dynamically loading images using urls should work like so:

<img :src="assets/path/to/img.png">

UPDATE May 9th:

In production the above does not work, the images are still rendered as assets/path/to/img.png where a path with _nuxt/.../.../ should be used to access the assets.

To dynamically render images that are currently existing within your assets directory, you will need to import them in your script tag.

For example,

<script>
import icon from '@/assets/images/icon.png'
export default { 
  data () { 
    return { image: icon}
  }
}
</script>

<template>
  <img :src="image">
</template>
</template

Again, this is for Nuxt 3

@paidge
Copy link

paidge commented Jun 15, 2022

Thanks @juancarlos-ctg. This solution works with Nuxt3. But how to import the image dynamically ?
My component has a String prop with the asset name and I would like to import the image depending on this prop.

@paidge
Copy link

paidge commented Jun 23, 2022

I'll try your solution. I finally put my images in the public folder. With this method, images are not compressed but I compressed them before with another tool.

@pravinfullstack
Copy link

Any straightforward solution for this ?

@kiketordera
Copy link

Yeah, I want to do something like this, but I can't:

 <img :src="require('@assets/'+img)" alt="">

@EmmyMay
Copy link

EmmyMay commented Jul 5, 2022

Yeah, I want to do something like this, but I can't:

 <img :src="require('@assets/'+img)" alt="">

Require does not work with vite which nuxt 3 uses

@steel89ita
Copy link

We now know that require does not work with vite,
but which could be the solution to import the image dynamically with ssr?

For example, I was importing the image using "require" and combining it with a string prop,
but can't see a way of doing something similar with vite ssr, as import.meta.url is not working.

@mjzarrin
Copy link

mjzarrin commented Jul 22, 2022

An example of changing images dynamically while using Vite:

<img :src="`/assets/${dynamic_image_name}.jpeg`"/>

Update:
It only worked on dev mode.

@EmmyMay
Copy link

EmmyMay commented Jul 22, 2022

An example of changing images dynamically while using Vite:

<img :src="`/assets/${dynamic_image_name}.jpeg`"/>

This works on SSR?

@alexiokay
Copy link

alexiokay commented Aug 13, 2022

Maybe use 'type': 'commonjs' in package.json and add this in your nuxt.config.ts file:

I have configuration like this, but nothing worked after building because of missing it I tried before many things, was googling for some hours reading documentations of rollup, nuxt, plugins, vite, commonjs etc. Then I went somewehere for 2 hours, I came back and repaired it within 5 minutes :D

import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'
import rollupNodePolyFill from 'rollup-plugin-node-polyfills'
`vite: {
    plugins: [
    ],
    resolve: {
      alias: {
          // This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill, 
          // see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts
          // process and buffer are excluded because already managed
          // by node-globals-polyfill
          util: 'rollup-plugin-node-polyfills/polyfills/util',
          sys: 'util',
          events: 'rollup-plugin-node-polyfills/polyfills/events',
          stream: 'rollup-plugin-node-polyfills/polyfills/stream',
          path: 'rollup-plugin-node-polyfills/polyfills/path',
          querystring: 'rollup-plugin-node-polyfills/polyfills/qs',
          punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',
          url: 'rollup-plugin-node-polyfills/polyfills/url',
          string_decoder: 'rollup-plugin-node-polyfills/polyfills/string-decoder',
          http: 'rollup-plugin-node-polyfills/polyfills/http',
          https: 'rollup-plugin-node-polyfills/polyfills/http',
          os: 'rollup-plugin-node-polyfills/polyfills/os',
          assert: 'rollup-plugin-node-polyfills/polyfills/assert',
          constants: 'rollup-plugin-node-polyfills/polyfills/constants',
          _stream_duplex:
              'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',
          _stream_passthrough:
              'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',
          _stream_readable:
              'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',
          _stream_writable:
              'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',
          _stream_transform:
              'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',
          timers: 'rollup-plugin-node-polyfills/polyfills/timers',
          console: 'rollup-plugin-node-polyfills/polyfills/console',
          vm: 'rollup-plugin-node-polyfills/polyfills/vm',
          zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',
          tty: 'rollup-plugin-node-polyfills/polyfills/tty',
          domain: 'rollup-plugin-node-polyfills/polyfills/domain'
      },
    },
    optimizeDeps: {
      esbuildOptions: {
          // Node.js global to browser globalThis
          define: {
              global: 'globalThis'
          },
          // Enable esbuild polyfill plugins
          plugins: [
              NodeGlobalsPolyfillPlugin({
                  process: true,
                  buffer: true
              }),
              NodeModulesPolyfillPlugin()
          ]
      }
  },

    build: {
      rollupOptions: {
        plugins: [
            // Enable rollup polyfills plugin
            // used during production bundling
            rollupNodePolyFill()
        ]
    }
  },`

@terwer
Copy link

terwer commented Aug 25, 2022

Still not work

@den-kar
Copy link

den-kar commented Aug 28, 2022

I kind of found a work-around by replacing <img> with a <div> and setting the background-image with a Tailwind class.
Changed from:

const logoFilename = 'logo-1.svg';
<img :src="`~/assets/img/logos/${logoFilename}`" ... />

to:

const logoTailwindBgImage = 'bg-[url(~/assets/img/logos/logo-1.svg)]'
<div class="w-full ..." :class="logoTailwindBgImage" ...></div>

This works in production too, but only when passing the whole Tailwind class as a single string.

Concatenating the class name only works with yarn dev:

const concatenatedTailwindClass = `bg-[url(~/assets/img/logos/${logoFilename})]`
<div class="w-full ..." :class="concatenatedTailwindClass" ...></div>

yarn build exits with an error:

ERROR [vite:css] ENOENT: no such file or directory, open 'path/to/project/root/assets/img/logos/${logoFilename}'
file: /path/to/project/root/assets/css/tailwind.css

ERROR ENOENT: no such file or directory, open '/path/to/project/root/assets/img/logos/${logoFilename}'

error Command failed with exit code 1.

It's no one-to-one replacement, but at least the images are rendered in production and are available at e.g. http://www.example.io/_nuxt/logo-1.ccb82e2f.svg.

Might be helpful to someone

@slavco86
Copy link

slavco86 commented Sep 9, 2022

Trying to integrate Azure application insights with our Nuxt 3 app to monitor requests which Nuxt is making server side.
According to app insights docs - I have to use require in order to initialise the package, which I am trying to do via server side plugin, but like it was mentioned above - also getting an error saying required is not defined
https://www.npmjs.com/package/applicationinsights

Is there a work around?

Copy link
Member

Can you not import instead of require? (I would request that you move this to a discussion rather than a long-closed and unrelated issue.)

@slavco86
Copy link

slavco86 commented Sep 9, 2022

https://github.com/nuxt/framework/discussions/7391

@slavco86
Copy link

Can you not import instead of require? (I would request that you move this to a discussion rather than a long-closed and unrelated issue.)

No, the package doesn't support import - I'm getting undefined with import

@manniL
Copy link
Member

manniL commented Sep 12, 2022

Even with import * as MY_VAR from 'package'?

@slavco86
Copy link

Bingo!
Thanks!!!

@schnetzi
Copy link

schnetzi commented Oct 22, 2022

@slavco86 @manniL your discussion and solution is not related to this problem. The problem is/was to import/require a dynamic image path and not a package.

To the problem with loading dynamic images:
I found a solution in stack-overflow: https://stackoverflow.com/a/71514878/7866722

My solution turned out like that

const imageUrl = new URL(`../../assets/images/${props.src}`, import.meta.url).href;

Although I am getting the following error now:

Not allowed to load local resource file:///Users//projects//assets/images/logo.png

Full code for an Article Image with Nuxt Content
<!-- components/content/ArticleImage.vue -->
<template>
  <img :src="imgSrc()" :alt="alt" class="article-image" />
</template>

<script setup lang="ts">
const props = defineProps<{
  src: string;
  alt: string;
}>();

function imgSrc() {
  try {
    const imageUrl = new URL(`../../assets/images/${props.src}`, import.meta.url).href;

    return imageUrl;    
  } catch (error) {
    console.error(error);
  }
}
</script>

Copy link
Member

Check out https://vitejs.dev/guide/features.html#glob-import and follow #14766.

@danielroe danielroe added the 3.x label Jan 19, 2023
@danielroe danielroe transferred this issue from nuxt/framework Jan 19, 2023
@miumerfarooq
Copy link

For dynamic images use this, it works in nuxt 3.
Define the path as I did.

<template>
  <div class="app">
    <img :src="`/_nuxt/assets/images/${img.src}`" alt="image"/>
  </div>
</template>

export default {
  data() {
    return {
      img: { 
        src: 'img.png' 
      }
    }
  }
}

Note: define your directory properly, my image are saved in images folder.

It work for me :)

@kissu
Copy link

kissu commented Jan 24, 2023

For dynamic images use this, it works in nuxt 3. Define the path as I did.

<template>
  <div class="app">
    <img :src="`/_nuxt/assets/images/${img.src}`" alt="image"/>
  </div>
</template>

export default {
  data() {
    return {
      img: { 
        src: 'img.png' 
      }
    }
  }
}

Note: define your directory properly, my image are saved in images folder.

It work for me :)

That one is more of a local-dev only thing.
I don't think it would work once pushed to production (since _nuxt is used as a local cache).

@itskush
Copy link

itskush commented Feb 23, 2023

what if im trying to pass an object? like a json to a component's props (which is expecting an object)?
for example :loaData:require('@/assets/data.json')

@itskush
Copy link

itskush commented Feb 23, 2023

I manged to get it working via a function in methods

@leo95batista
Copy link

I have the same problem, what I'm trying to do is something like this: <template> <svg class="inline-block overflow-hidden" height="1em" width="1em"> <use :xlink:href="`~/assets/icons/core.svg#${props.name}`"></use> </svg> </template>

but it renders in the DOM as <use :xlink:href="~/assets/icons/core.svg#icon1"></use>

@GavinJaynes
Copy link

It's ridiculous that it's so complicated to get a dynamic image path in Nuxt. Surely, there's a better way?

Thanks to #12797 (comment)

This seems to work, but I don't like that the path is so fickle (relative) - it would be good if the alias worked:
const imageUrl = new URL(`~/assets/images/${props.backgroundImageName}`, import.meta.url).href;

A working solution in Nuxt 3 using SFC ✅

<script lang="ts" setup>

const props = defineProps<{
  backgroundImageName: string;
}>()

const getImageSrc = () => {
  try {
    const imageUrl = new URL(`../assets/images/${props.backgroundImageName}`, import.meta.url).href;
    return imageUrl;
  } catch (error) {
    console.error(error);
  }
}
</script>

<template>
      <img :src="getImageSrc()" alt="background image" />
</template>

@hakimov-dev
Copy link

Any news ? Have you guys find solution for that?

@Kaperskyguru
Copy link

Any solution? Doesn't work in Production with Netlify

@Kaperskyguru
Copy link

Kaperskyguru commented Apr 13, 2024

I found a workaround that works for me.

I moved all the images to the public folder and used this code.

     <img
          class="w-full h-full object-fill"
          :src="`/img/${props.item?.image}`"
          :alt="item?.title"
        />

It worked in both dev and prod


I write a lot about Vue 3 and Nuxt 3 at enterprisevue.dev

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests