tonymx227
tonymx227

Reputation: 5451

Import path using variable SASS

I'd like to import a file using variables.

My code (that doesn't work) :

$input-field-theme: default;
@import '#{$input-field-theme}';

Error message : Error: File to import not found or unreadable: #{$input-field-theme}

And this works : @import 'default';

Upvotes: 18

Views: 21824

Answers (3)

Mario Araque
Mario Araque

Reputation: 4572

At this moment it is not possible, check this GitHub issue logged against Sass in 2012 for more information.

The reasoning given there is as follows:

Allowing dynamic imports would completely break Sass's ability to quickly determine which files import which other files, and thus what needs re-compiling when.

That thread also includes a link to another issue which includes this 2018 comment that discusses future plans for dynamic dependencies:

I'm locking this issue for now because there's a lot of noise without a lot of value being added. To summarize, this is the plan:

The new @use directive will provide the ability to import a file as a mixin, so you can dynamically decide whether and where to include it. This will bring Sass more in line with other languages that work well without dynamic imports, since it means importing no longer has unavoidable side-effects.

We will add a load() function as described above that will allow stylesheets to load files at runtime based on variable values. This will support the more complex use-cases where stylesheets need to be loaded based on user input, while preserving the ability to statically trace the import graph and the mixins and functions it defines.

Upvotes: 11

Aakash
Aakash

Reputation: 23737

Webpack with SASS-LOADER : https://webpack.js.org/loaders/sass-loader/#additionaldata

We can add to the prependData property to sass-loader options:

{ 
  loader: 'sass-loader',
  options: {
    additionalData: '$env: ' + process.env.NODE_ENV + ';',
  }
}

Note: prependData can be a function too which receives loader-context.

Good Luck...

Upvotes: 2

Nelly Sattari
Nelly Sattari

Reputation: 2763

Alternative solution is, if you used Gulp to compile your SASS file,you need to introduce the includePaths to the config. Then once you import any module from a folder it considers looking at the paths you introduced already in "includePaths". Ex)

gulp.task(`compileSASS`, function () {
   return gulp.src(`styles/main.scss`)
    .pipe(sass({
        outputStyle: `expanded`,
        precision: 10,
        includePaths: [
            '../../../feature',
            '../../..',
        ]    
    })
    .pipe(gulp.dest(`temp/styles`));
    });

Now that you setup your code you can import files from various paths:

 @import "promotion/code/styles/_promotion.scss";

To import this file, it will look at all "includePaths".

Upvotes: 3

Related Questions