1

I know this probably gets asked often, but I've looked at several similar questions, but can't quite figure out how to resolve URLs in this scenario.

Note: I am NOT using a dev server or any special framework; just Webpack and opening files through the browser (file://). The Webpack-built files must work without a server, so please do not suggest using one. Also, I'm using Webpack 3.

File structure:

src/
- assets/
  - img/
    - backgrounds/
      - some-bg.jpg
  - css/
    - layouts.css
- index.html
- main.js
node_modules/
webpack.conf.js

layouts.css references some-bg.jpg as a background image:

body {
    background-image: url('../img/backgrounds/some-bg.jpg');
}

In my Webpack config, I have:

module.exports = {
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: 'bundle.js'
    },
     module: {
         loaders: [
           {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    use: "css-loader",
                    fallback: "style-loader"
                })
           },
           {
                test: /\.(jpe?g|png|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        limit: 8192,
                        name: "./assets/img/[name].[ext]"
                    }
                }
           }
        ]
    }
    plugins: [
        new ExtractTextPlugin({
            filename: "./assets/css/style.css"
        }),
    ]
// ...
}

All of the images referenced in index.html are correctly changed to ./assets/img/whatever.png.

However, the background-image url is changed to url(./assets/img/some-bg.jpg), which points to the path dist/assets/css/assets/img/some-bg.jpg.

What do I have to change to get the url to simply be dist/assets/img/some-bg.jpg?

1 Answer 1

1

Finally got it working. With this specific structure, I had to specify a publicPath on the ExtractTextPlugin (even though I did not have a regular publicPath set for Webpack itself).

{
  test: /\.css$/,
  use: ExtractTextPlugin.extract({
    use: "css-loader",
    fallback: "style-loader",
    publicPath: "../../"
  })
},
Sign up to request clarification or add additional context in comments.

1 Comment

And then? What are you meant to do with background-image: url('...')?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.