bholloway / resolve-url-loader

Webpack loader that resolves relative paths in url() statements based on the original source file
563 stars 71 forks source link

Custom Join Implementation to rewrite url() paths #236

Open jordwms opened 4 months ago

jordwms commented 4 months ago

I have a webpack config using your amazing tool. The default implementation works great. However, I have a special circumstance for Storybook. As storybook runs from localhost I get errors when trying to use fonts hosted on external domains (e.g. url('https://www.my-domain.com/fonts/icons.woff')).

To circumvent this, I would like to have resolve-url-loader instead find those font files in a local, relative directory to the SCSS partial files in question (a sibling directory, in fact, to the SCSS which references the font files - located in node_modules/@package-name/styles/fonts).

After diving through your code and docs I came up with a shoddy implementation for a custom join function like so:

{
    loader: require.resolve("resolve-url-loader"),
    options: {
        debug: true,
        // join: myJoinFn
        join: createJoinFunction(
            'myJoinFn',
            createJoinImplementation( asGenerator(
                ({ uri, isAbsolute, bases: { subString, value, property, selector } }, { root }) => {

                    // Match URLs starting with "https://www.my-domain.com/_assets/fonts/"
                    if (uri.contains('https://www.my-domain.com/_assets/fonts/')) {
                        // Remove the leading "https://www.my-domain.com/_assets/fonts/" part
                        const loc = uri.slice(31);

                        // Construct the new path with "../fonts/" and the remaining path
                        return ['../fonts/', loc];
                    } else {
                        // Use the default join functionality for other URLs
                        return [base, uri];
                    }
            })
        ))
    }
},

Based on the docs it is unclear to me as to how to set debug flags and where to find output from the debug. And moreover, since I don't have a reasonable way to debug I don't know if my approach is wrong-headed.

I appreciate any response or discussion. Thank you for your time!

bholloway commented 4 months ago

Haven’t had a chance to look in detail but i can talk about debug.

IIRC there is a debug option in the loader configuration object which it looks like you are using.

You may do better to just put a temporary console.error() in your implementation or in the node modules loader. Any console.log() will probably be swallowed by webpack.