Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webpack alias resolve #60

Open
Hulkmaster opened this issue Aug 22, 2019 · 4 comments
Open

Webpack alias resolve #60

Hulkmaster opened this issue Aug 22, 2019 · 4 comments

Comments

@Hulkmaster
Copy link

I am using postcss with webpack, and i want to use webpack resolver for paths like

~@Images/svg/icon.svg

but i guess that plugin doesnt use webpack resolver, or am i wrong?
maybe there is a postcss plugin, which resolves path using webpack resolver, so i could preprocess path?

@TrySound
Copy link
Owner

Was already asked #46

@Hulkmaster
Copy link
Author

Hulkmaster commented Aug 22, 2019

I'm not sure if it is really hard to implement, becuase if you have access to loaderContext, then you can just try to resolve it with loaderContext.resolve('', '@Images/svg/icon.svg', (error, result)=>{}). and in result you'll have absolute path (that will work, if @Images is defined in webpack.resolve.alias)

For anyone, who will look into that issue, here is an example how to solve it with sass-loader
(sass-loader should be below (before) postcss loader)

          {
            loader: 'sass-loader',
            options: {
              functions: (loaderContext) => ({
                'getPath($filePath)': function(filePath, done) {
                  /**
                   * That loader helper function will resolve webpack aliased imports into absolute strings
                   * getPath("~@Images/icon.svg") -> /var/www/app/static/img/icon.svg
                   * 
                   * Sass import might include webpack alias (like ~@Images/)
                   * These aliased imports always start with '~', so if we see one - we modify it into valid webpack alias
                   */
                  const filePathValue = filePath.getValue();
                  const resultPath = filePathValue.indexOf('~') !== -1 ? filePathValue.substr(1) : filePathValue;
                  loaderContext.resolve('', resultPath, (error, result)=>{
                    if (error) {
                      throw error;
                    }
                    const SassString = require('node-sass').types.String;
                    done(SassString(result));
                  });
                },
              }),
            },
          },

@TrySound
Copy link
Owner

This is postcss plugin. It does not know anything about webpack.

@Hulkmaster
Copy link
Author

maybe there is something in postcss plugin api for resolving?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants