When using SASS how can I import a file from a different directory?

Viewed 139534

In SASS, is it possible to import a file from another directory? For example, if I had a structure like this:

- root_directory
    - sub_directory_a
        - _common.scss
        - template.scss
    - sub_directory_b
        - more_styles.scss

template.scss could import _common.scss using @import "common" but is it possible for more_styles.scss to import _common.scss? I tried a few different things including @import "../sub_directory_a/common" and @import "../sub_directory_a/_common.scss" but nothing seems to work.

14 Answers

node-sass (the official SASS wrapper for node.js) provides a command line option --include-path to help with such requirements.

Example:

In package.json:

"scripts": {
    "build-css": "node-sass src/ -o src/ --include-path src/",
}

Now, if you have a file src/styles/common.scss in your project, you can import it with @import 'styles/common'; anywhere in your project.

Refer https://github.com/sass/node-sass#usage-1 for more details.

If using Web Compiler in Visual Studio you can add the path to includePath in compilerconfig.json.defaults. Then there is no need for some number of ../ since the compiler will use includePath as a location to look for the import.

For example:

"includePath": "node_modules/foundation-sites/scss",

The best way is to user sass-loader. It is available as npm package. It resolves all path related issues and make it super easy.

Related