Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

angular - SCSS Import Relative to Root

I'm in the process refactoring an Angular application and as I'm moving components around to new directory locations, I'm finding that dealing @import paths in the components' SCSS files is getting a bit tedious.

For example, let's say I have the file src/_mixins.scss in the root of my application and the component src/app/my-widget/my-widget.component.scss imports the SCSS like so @import '../../mixins';. All well and good.

But then I decide that my-widget.component is really be a "shared component" under another component my-thingy.component, so I create a shared folder under src/app/my-thingy and move everything that was in src/app/my-widget into it.

I hope you're still with me... So, now I've got src/app/my-thingy/shared/my-widget and I modify my SCSS file to import @import '../../../../mixins'.

Note: This is a simplified example. Some of the paths get relatively deep (no pun intended... or was it?) and all of these . and / are a bit much.

TL;DR

It would be super-handy if from the start I could have just imported _mixins.scss relative to the root in all of my components' SCSS files so I don't have to keep messing with the @import paths when refactoring. (e.g. Something along the lines of @import '~/mixins'). Does something like this exist?

What I've tried (and, sadly, has failed):

  1. @import '~/mixins'; /** I had real hope for this one **/
  2. @import 'mixins'; /** Just being overly optimistic here **/
  3. @import '~//mixins'; /** Now I'm just making stuff up **/

I understand that I'm already going to have to modify my mod files to point to the new path of the component with all of this "moving stuff around", but... hey, one less thing, right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • If you are using Angular CLI, take a look at Global styles, "stylePreprocessorOptions" option specifically.
  • For webpack, you can configure includePaths in sassLoader plugin configuration.
  • And it's similar for gulp builds, you pass includePaths to the sass plugin.

Whatever your build tool is, sass will treat those paths as root, so you can import them directly, so with:

includePaths: ["anywhere/on/my/disk"]

you can just @import 'styles' instead of @import 'anywhere/on/my/disk/styles'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...