使用 Rails 6.1 和 sass-loader 自动包含所有嵌套的 SCSS 文件
在 Rails 6.0.3.4 中,可以使用 Sass-loader 来 glob 所有 SCSS 文件,而无需手动包含每个文件。
问题 - 语法 v7
这在 Rails 6.1 中失败,出现以下 webpacker 错误(使用 webpacker 配置,见下文.options = { importer: globImporter() }; // syntax for sass-loader v7
)
ERROR in ./app/javascript/packs/application.scss (./node_modules/css-loader/dist/cjs.js??ref--6-1!./node_modules/postcss-loader/src??ref--6-2!./node_modules/sass-loader/dist/cjs.js??ref--6-3!./app/javascript/packs/application.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
ValidationError: Invalid options object. Sass Loader has been initialized using an options object that does not match the API schema.
- options has an unknown property 'importer'. These properties are valid:
object { implementation?, sassOptions?, prependData?, sourceMap?, webpackImporter? }
at validate (/workspace/node_modules/sass-loader/node_modules/schema-utils/dist/validate.js:98:11)
at Object.loader (/workspace/node_modules/sass-loader/dist/index.js:36:28)
问题 - 语法 v8
如果我将配置更改为 sass-loader v8 语法(.sassOptions = { importer: globImporter() };
),我会得到不同的错误:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.module.rules[2].use[3] has an unknown property 'sassOptions'. These properties are valid:
object { ident?, loader?, options?, query? }
问题
如何使用 Rails 6.1 和 sass-loader v8 配置它?
6.1 之前的原始工作配置:
yarn add node-sass-glob-importer
, Rails 6.1 使用sass-loader@8.0.2
- 调整 webpack 配置以传递 loader 选项:
# config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const globImporter = require('node-sass-glob-importer');
environment
.loaders
.get('sass')
.use
.find(item => item.loader === 'sass-loader')
.options = { importer: globImporter() }; // syntax for sass-loader v7
// .sassOptions = { importer: globImporter() }; // for v8
module.exports = environment
- 然后在
// app/javascript/packs/application.scss
import './application.scss';
- 最后在
// app/javascript/packs/application.scss
@import '../stylesheets/**/*.scss';
然后,所有嵌套的 SCSS 样式表app/javascript/packs
都将被自动全局化。