postcss / postcss-url

PostCSS plugin to rebase url(), inline or copy asset.
MIT License
377 stars 60 forks source link

Having issues with `copy` and relative path to `to` #143

Open chopfitzroy opened 4 years ago

chopfitzroy commented 4 years ago

Hey so I have the following config (in rollup):

postcss({
    to: './public/dist/',
    extract: 'public/dist/app.css',
    plugins: [
        url({
            url: 'copy',
            useHash: true,
            assetsPath: './dist/',
        })
    ]
})

And the following CSS:

.hero {
    background-image: url("../images/hero.jpg");
}

Which is the closest I can get it to working, the image is in the right directory public/dist however the CSS path is background-image: url("dist/7d8c51c4.jpg");

This resolves to http://localhost/dist/dist/7d8c51c4.jpg as opposed to http://localhost/dist/7d8c51c4.jpg.

I am running a server in the public/ directory and essentially need the path to be /dist/7d8c51c4.jpg or alternatively ./7d8c51c4.jpg as the image is in the same root as the generated CSS file.

I have tried every possible variation I can think of with the to and assetPath arguments, but I either get the path right and the image in the wrong directory or the image in the right directory and the wrong path.

Cheers.

sergcen commented 4 years ago

Hi You have 2 options:

  1. assetsPath='.' // current directory == to, but i'm not shure
  2. fix url
    url([
    { url: 'copy', assetsPath: 'dist', useHash: true },
    { 
      url: (asset) => {
        return asset.url.replace('/dist', '') // result of previous step, can modify here
      }, 
      multi: true 
    }
    ])
    ;
chopfitzroy commented 4 years ago

So to be clear option 1 would be:

postcss({
    to: './public/dist/',
    extract: 'public/dist/app.css',
    plugins: [
        url({
            url: 'copy',
            useHash: true,
            assetsPath: '.', // So this changes an `to` stays the same?
        })
    ]
})

Otherwise option 2 looks good :)

chopfitzroy commented 4 years ago

Okay so the above code created the image in the public/ directory next to dist/.

I tried:

postcss({
    to: './public/dist/',
    extract: 'public/dist/app.css',
    plugins: [
        url({
            url: 'copy',
            useHash: true,
            assetsPath: './dist', // So this changes an `to` stays the same?
        })
    ]
})

Which put it in the right directory but the associate CSS is background-image: url("dist/7d8c51c4.jpg") which almost works but resolves to:

https://myapp.com/dist/dist/7d8c51c4.jpg

As opposed to"

https://myapp.com/dist/7d8c51c4.jpg

Because it does not include the / before dist/.