3
votes

I am having trouble with webpack and react serving static images on webpack dev server.

This is my currenct folder structure

enter image description here

As you can see I have a assets folder witch holds all my images This is my webpack entry and output configuration

enter image description here

Where client entry is source of my react project CLIENT_ENTRY: path.join(process.cwd(), 'src/client/index.jsx')

Now here is my output in BASH when webpack has done its part enter image description here

And here is where I am trying to load images from assets folder in root of the project

enter image description here

Only the import works witch is expected.

I have tried to change the output and public path like so in webpack path: path.resolve(__dirname, 'dist'), publicPath: '/',

path: path.resolve(__dirname, 'dist/assets'), publicPath: '/assets/',

path: path.resolve(__dirname, 'dist'), publicPath: '/assets',

path: path.resolve(__dirname, 'dist'), publicPath: '/assets/',

etc.. etc..

If someone could help me that would be great

2
I forgot to mention that in my src/server/server.js I am using express and serving static content like so // Serve static content for the app from the assets directory and build directory app.use(express.static('build')); app.use(express.static('assets'));jonjonson
Are they in a relative path to the outputted Main.js? Otherwise it clearly wouldn't work. You can have them in your source and build with with Webpack, if you test for .jpg. I do something like: { test: /\.(ttf|otf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?|(jpg|gif)$/, loader: 'file-loader?name=./static/fonts/[name].[ext]' } cbll
Yes they are like so <script defer src="${ assets ? assets.main.js : '/main.js' }" ></script>jonjonson
So something like const file = { test: /\.(woff2?|jpe?g|png|gif|ico)$/, use: 'file-loader?name=./assets/images/[name].[ext]' };jonjonson
Something along those lines, yes. Give it a shot and update your javascript to include the relative path of the outputted images and let me know.cbll

2 Answers

1
votes

To follow the idea behind webpack you need to process assets from your source to your target.

Therefore, add your images to a relative path in your source (where your entry is, essentially) and add a loader for the images (and perhaps other things) as such:

{
    test: /\.(woff2?|jpe?g|png|gif|ico)$/, 
    use: 'file-loader?name=./assets/images/[name].[ext]'
}

Just update the relative path of the outputs to the assets/images and they should be able to load.

2
votes

In your webpack.config.js, you will need to serve the assets folder as well.

{
  ...webpack,
  devServer: {
    contentBase: [__dirname + '/public', __dirname + '/assets'],
    ...webpack.devServer,
  },
}