使用 Storybook 导入 scss 文件

import scss file with Storybook

我目前遇到 Storybook 的问题。使用 webpack,我的应用程序中的一切都运行良好。 Storybook 似乎对我的配置有问题。

这是我的 webpack.config.js :

module.exports = {
   entry: './index.js',
   output: {
   path: path.join(__dirname, 'dist'),
   filename: 'bundle.js'
},
module: {
   loaders: [
   {
      test: /\.js$/,
      loader: 'babel-loader',
      exclude: /node_modules/,
      include: __dirname
   },
   {
      test: /\.scss$/,
         use: [
         {loader: "style-loader"}, 
         {loader: "css-loader"},
         {loader: "sass-loader",
          options: {
            includePaths: [__dirname]
    }
  }]
},

Storybook 在解析 scss 文件时遇到问题,我是否需要为 Storybook 创建一个特定的 webpack.config.js 来解决这个问题?

在我的主应用程序中,我以这种方式导入我的 scss 文件:import './styles/base.scss'

只需添加一个与我现有的非常相似的 webpack.config.js 即可奏效:

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]'
          }
       }
     }
   ]
 }
}

对于 Create React App 上的 运行 故事书,将 MiniCssExtractPlugin 添加到 .storybook/webpack.config.jon 解决了我加载 sass 文件的问题:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = function({ config }) {
  config.module.rules.push({
    test: /\.scss$/,
    loaders: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
    include: path.resolve(__dirname, '../')
  });

  config.plugins.push(new MiniCssExtractPlugin({ filename: '[name].css' }))

  return config;
};

Credits to Nigel Sim!

故事书 6 中有 main.js 的简单代码,对我来说效果很好!

const path = require('path');

// Export a function. Accept the base config as the only param.
module.exports = {
  stories: [...],
  addons:[...],
  webpackFinal: async (config, { configType }) => {
    // `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
    // You can change the configuration based on that.
    // 'PRODUCTION' is used when building the static version of storybook.

    // Make whatever fine-grained changes you need
    config.module.rules.push({
      test: /\.scss$/,
      use: ['style-loader', 'css-loader?url=false', 'sass-loader'],
      include: path.resolve(__dirname, '../'),
    });

    // Return the altered config
    return config;
  },
};