1

I'm wondering what the best way is to get the asset path for things like images from inside a React component. I'm using Laravel, and the built-in asset() function that you can use in Blade files is exactly what I need, but I need it on the front-end in JS. Seems like Webpack territory, but I'm not sure what setting I need to modify.

The problem arises when my path is more than just the hostname, for example "localhost:3000/myproject/public" instead of just "localhost:3000".

Doing something like....

import myImage from '../../images/my-image.png'

...

<img src={myImage} />

results in a src path of "/images/my-image.png", which is not found, because the image actually resides at "/myproject/public/images/my-image.png"

In the past I've used the not-so-elegant solution of doing:

// react.blade.php
<body data-root-url={{ asset('') }}>
  ...
</body>

// helpers.js
export const rootUrl = document.querySelector('body').getAttribute('data-root-url')

While this hasn't gotten me into any trouble yet, I'm trying to find a better way, and I also started using Typescript recently and it (understandably) gets cranky about this because it technically could be null.

I've also tried the following in webpack.mix.js:

  mix.webpackConfig({
    output: {
      publicPath: 'http://localhost:3000/myproject/public/',
    },
  })

but that doesn't seem to have any effect on image paths. Oddly enough though, this did work when running into a similar issue with code-splitting and looking for the JS chunks.

Any thoughts? Thanks!

hello_luke
  • 837
  • 12
  • 15

1 Answers1

0

I fix it by adding a new controller in the routes/web.php file.

Route::get('assets/{path}', function ($path) {
    return response()->file(public_path("assets/$path"));
});

Then I added the images inside the folder public/assets/img/test.jpg and called it in my React component normally.

<Card sectioned>
  <EmptyState image="/assets/img/test.jpg">
  </EmptyState>
</Card>
Rafael Corrêa Gomes
  • 1,751
  • 1
  • 22
  • 31