Strangely, the loadPaths attribute doesn't work, what worked for me was using includePaths:
{
loader: 'sass-loader',
options: {
sassOptions: {
includePaths: [path.resolve(__dirname, 'Develop', 'Styles')]
}
}
}
Answer from violetflare on Stack OverflowYou can use Webpack aliases. Resolving every import /templates to your project's templates/ folder.
const path = require('path');
module.exports = {
// ...
resolve: {
alias: {
'/templates': path.resolve(__dirname, './templates')
}
}
};
I read @sympony/webpack-encore and found addAliases setting. You can use as the following example.
const path = require('path');
const Encore = require('@symfony/webpack-encore');
Encore
// ...
.addAliases({
'/templates': path.resolve(__dirname, './templates')
});
In your Scss/SASS on import use ~ ahead file path.
@import '~/templates/common/variables'
- Webpack alias reference
@symfony/webpack-encoreaddAliasesreferencesass-loaderimport reference
Probably you already found the answer yourself, but just in case some else gets here the common way of using url() with paths relatives to the file where they are imported is using resolve-url-loader. Also note that you have to set the sourceMap to true in the preceding loaders.
https://www.npmjs.com/package/resolve-url-loader
That's an example on how to use it:
{
// Note that sourceMap is needed to be true at least in sass-loader so resolve-url-loader works fine
test: /\.scss$/,
use: [
{
loader: "style-loader",
options: { sourceMap: true }
}, // Adds CSS to the DOM by injecting a <style> tag
{
loader: "css-loader",
options: { sourceMap: true }
}, // The css-loader interprets @import and url() like import/require() and will resolve them.
{
loader: "postcss-loader",
options: {
sourceMap: true,
plugins: [
require("autoprefixer")({ browsers: ["last 2 versions"] })
]
}
}, // Adds prefix for cross-browser support
{
loader: "resolve-url-loader",
options: { sourceMap: true }
}, // Webpack loader that resolves relative paths in url() statements based on the original source file.
{
loader: "sass-loader",
options: { sourceMap: true }
} // Loads a Sass/SCSS file and compiles it to CSS.
]
}
» npm install sass-loader
The error comes from webpack-validator because it doesn't recognize the sassLoader property. You need to configure a schema extension:
const Joi = require('webpack-validator').Joi
const schemaExtension = Joi.object({
sassLoader: Joi.any(),
})
module.exports = validate(config, {schemaExtension: schemaExtension})
Requiring CSS modules is handled by the css-loader, only @import is handled by sass-loader. (There are major differences in their behaviour other than that, make sure you are using what you need).
In order to require from the root directory, you need to configure resolve.root in the webpack config file. See answer here: Resolving require paths with webpack