正在 Storybook 和 Angular 中加载 scss 文件:需要 1 个选择器或规则,是 "var content = requi"

Loading scss files in Storybook & Angular: expected 1 selector or at-rule, was "var content = requi"

我正在尝试为我的 angular 项目设置故事书。但是,当尝试为组件设置第一个故事时,出现以下错误:

ERROR in ./src/app/modules/ka-basic-components/ka-button/ka-button.component.scss
Module build failed:
@import '~styles/helpers/variables';
^
  File to import not found or unreadable: ~styles/helpers/variables.

然后我添加了一个具有以下规则的 webpack 配置:

const path = require('path');

module.exports = {
  module: {
    rules: [{
        test: /\.scss$/,
        loaders: ['style-loader', 'css-loader', 'sass-loader'],
        include: path.resolve(__dirname, '../')
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader',
        include: __dirname
      },
      {
        test: /\.(woff|woff2)$/,
        use: {
          loader: 'url-loader',
          options: {
            name: 'fonts/[hash].[ext]',
            limit: 5000,
            mimetype: 'application/font-woff'
          }
        }
      },
      {
        test: /\.(ttf|eot|svg|png)$/,
        use: {
          loader: 'file-loader',
          options: {
            name: 'fonts/[hash].[ext]'
          }
        }
      }
    ]
  }
};

现在,我收到以下错误:

ERROR in ./src/app/modules/ka-basic-components/ka-button/ka-button.component.scss
Module build failed:
@import '~styles/helpers/variables';
^
      Invalid CSS after "": expected 1 selector or at-rule, was "var content = requi"

我的研究表明这个错误通常意味着存在多个 .scss 测试,但是我没有任何其他 webpack 配置。我正在使用默认的故事书配置,这是我的 index.stories.ts:

import { storiesOf } from '@storybook/angular';
import { text, boolean } from '@storybook/addon-knobs';
import { KaButtonComponent } from '../app/modules/ka-basic-components/ka-button/ka-button.component';

storiesOf('Button', module).add('Primary', () => ({
    component: KaButtonComponent,
    props: {
        text: text('text', 'Button text'),
        disabled: boolean('disabled', true)
    },
    moduleMetadata: {}
}));

有没有人知道这个错误可能来自哪里以及我该如何解决?谢谢!

问题是 webpack 不知道如何处理 scss 文件中 import 语句的 ~styles 位。解决方案是在 webpack 配置中定义别名并省略 scss 加载器:

const path = require('path');

module.exports = {
    resolve: {
        alias: {
            styles: path.resolve(__dirname, '../src/styles')
        }
    }
};