devowlio / wp-react-starter

🚀WordPress Plugin Boilerplate using modern web techs like TypeScript, SASS, and so on... on top of a local development environment with Docker and predefined GitLab CI for continous integration and deployment!
https://devowl.io/wp-react-starter/
Other
387 stars 51 forks source link

How to add static assets (images)? #14

Closed nagyv closed 5 years ago

nagyv commented 5 years ago

Hi,

how would you add static assets to your React frontend?

This is what I've tried:

add file-loader to webpack config:

{
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          'file-loader'
        ]
      }

then in my react code do

import HatImage from '../../assets/hat_random.png'
...

   <img src={`/wp-content/plugins/wsb-players/public/dist/${HatImage}`}  />

The above works, but I don't like hardcoding the path to the image. Especially, as it does not work well with npm run dev / npm run build. Do you have a better approach for loading images?

matzeeable commented 5 years ago

Hi!

In my plugins I am working with a localized variable. Please see the above commit https://github.com/matzeeable/wp-reactjs-starter/commit/4e1fea8d90d5287871b4f52c350c533ce1bf961c so you can add it to your Assets.class.php file. The publicUrl looks then like this: https://example.com/wp-content/plugins/your-plugin/public/.

In your frontend you can use that variable:

<img src={ (window.wprjssOpts.publicUrl + 'images/icon.png') }  />

You have to replace the WPRJSS term with your constant names.

nagyv commented 5 years ago

Thanks!

Matthias Günter notifications@github.com ezt írta (időpont: 2019. márc. 22., P, 16:46):

Hi!

In my plugins I am working with a localized variable. Please see the above commit 4e1fea8 https://github.com/matzeeable/wp-reactjs-starter/commit/4e1fea8d90d5287871b4f52c350c533ce1bf961c so you can add it to your Assets.class.php file. The publicUrl looks then like this: https://example.com/wp-content/plugins/your-plugin/public/.

In your frontend you can use that variable:

<img src={ (window.wprjssOpts.publicUrl + 'images/icon.png') } />

You have to replace the WPRJSS term with your constant names.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/matzeeable/wp-reactjs-starter/issues/14#issuecomment-475672082, or mute the thread https://github.com/notifications/unsubscribe-auth/AAHuzxveP8FFMRH5PQIVrJx1S9VksVAjks5vZProgaJpZM4cDg_4 .