How to use variables in different less files?

2019-04-09 00:09发布

问题:

Let's say I separate a less files into many less files to be easy to organize. Here is my repository:

/reset.less
/variables.less
/mixins.less
/main.less
/styles.less 

The styles.less is just importing the other files:

@import "reset.less";
@import "mixins.less";
@import "variables.less";
@import "main.less";

However, when I add some codes into main.less and use the @line-color which is defined in the variables.less. It shows Name Error: variable @line-color is undefined and I cannot compile it- I use PHPStorm with less plugin.

Could you pleas suggest me?

回答1:

You have to import your variables.less to all files which use your variables.

Edit:

You have to compile only your style.less. You cannot compile the main.less because it doesn't know the variables.less but you don't want a main.CSS anyway, do you?
You should get the correct style.css which is (I guess) the only css file you'll need.



回答2:

I could solve it by doing the following in PHPstorm:

  • Open Preferences…
  • In Tools > File Watchers > Less (configure)
  • Check "track only root files"
  • Change the "Output paths to refresh" to ../css/$FileNameWithoutExtension$.css (added "../css/" in front - depending on what folder you'd like to write the css files into)
  • (At this point you may want to check if this already does the job to your liking. If it doesn't, carry on to the next step…)
  • In Other Settings > LESS Profiles > (Your profile) (configure)
  • Define "LESS source directory": /Users/macuser/htdocs/MySite/sites/all/themes/mytheme/less (depending on which folder contains the .less files)
  • Define "Include file by path": /Users/macuser/htdocs/MySite/sites/all/themes/mytheme/less/style.less (file name depending on which .less file compiles the other .less files)
  • Add "CSS output directory" by selecting the folder you wish to write the (minified) CSS files
  • Enable Compress CSS output if desired

Notice: If Compress CSS output is enabled, this means that the code will be compressed everytime you right-click a .less-file and hit "Compile to CSS". By default the output will not be compressed with every modification you make to the .less-file. If you do want to compress the CSS straight away,

  • Install less-plugin-clean-css using the following command in Terminal: sudo npm install -g less-plugin-clean-css
  • Next, go to Tools > File Watchers > Less (configure), and change the "Arguments" to --clean-css --no-color $FileName$ (added "--clean-css" in front). Now it will compile your CSS automatically while you're coding. You'll no longer need to compile manually.


标签: less