webpack (with sass-loader) - scss file @import does not recognize resolve alias
Solution 1
I was able to use, on a stylesheet, an alias that I defined in webpack by using the following:
@import '~alias/variables';
just by prefixing the alias with ~
did the trick for me, as suggested by documentation in here
Solution 2
Another fix related to this subject, remove .scss
@import '~scss/common.scss';
should be
@import '~scss/common';
Solution 3
Since your webpack.config.js
file is already in the /app
folder, shouldn’t the alias be:
resolve: {
alias: {
styles: path.join(__dirname, 'styles')
}
}
?
Solution 4
In my case the dependency is a node module, therefore I can import it like this:
@import '~node-module-name/variables';
And when using the actual node module dir name, my editor (PhpStorm) is not showing unresolved path error anymore (the problem which @tkiethanom mentioned). It looks like I need to specify alias in webpack config if I want to use sass style imports (e.g. my-package/colors
instead of my-package/_colors.scss
), and it seems it doesn't matter what is the name of that alias, as long as I use node module directory name
tome
Updated on July 09, 2022Comments
-
tome almost 2 years
My project structure:
webpack.config.js app-- --> src ---->> components ------>>> myComponent.js ------>>> myComponent.scss --> styles ---->> variables.scss
In webpack.config module.exports:
... resolve: { alias: { styles: path.join(__dirname, 'app/styles') } }
In my file - myComponent.scss:
@import "styles/variables";
I am getting this error when building bundle.js:
Module build failed: @import "styles/variables"; ^ File to import not found or unreadable: styles/variables
How can I @import aliases in sass files?
-
tome over 8 yearsSorry, that was a mistake. Webpack.config is on the top level dir, edited question accordingly
-
CrocoDillon over 8 yearsOkay, already thought that’d be too easy. I’d have commented instead of answered but not enough rep.
-
tkiethanom almost 7 yearsThis works great but how do you get your editor to stop complaining about it. Obvisouly ~alias directory doesn't exist.
-
Admin over 6 years2018 and stuck at this. I'm using @material packages and they are all without tilde character!! so sass-loader gets stuck at subsequent imports. Tried adding an alias for
@material
and point topath.resolve(__dirname, 'node_modules/@material')
with no luck. Asked a question stackoverflow.com/questions/48368639/… -
A. L over 5 years@tkiethanom for you and anyone else who comes across this answer, see CrocoDillon's answer. Basically, if your config file looks exactly the same as his, you would use:
@import '~styles/variables';
-
Nathan over 5 years@tkiethanom Not sure about other editors, but IntelliJ/PhpStorm will use webpack.config.js to resolve imports, so it recognizes aliases.
-
higimo about 3 yearsUsing
~
is deprecated and can be removed from your code.