webpack (with sass-loader) - scss file @import does not recognize resolve alias

試著忘記壹切 提交于 2019-11-26 20:07:58

问题


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?


回答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




回答2:


Another fix related to this subject, remove .scss

@import '~scss/common.scss';

should be

@import '~scss/common';



回答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') 
   }
}

?




回答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



来源:https://stackoverflow.com/questions/34717203/webpack-with-sass-loader-scss-file-import-does-not-recognize-resolve-alias

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!