webpack 3 sass-loader无法导入没有相对路径的scss文件

问题描述 投票:0回答:1

我在webpack 3.10.0开始的React项目中使用create-react-app。我正在尝试调整我的Webpack配置,以便我可以导入没有相对路径的scss文件。

例如@import ../../scss_variables/vars.scssmyComponent.module.scss完美地运作,但我希望能够简单地使用@import scss_variables/vars.scss。我认为以下配置可以解决问题,但经过多次尝试后,我无法让@import工作。我收到以下错误:

Module build failed:
@import "scss_variables/vars.scss";
^
File to import not found or unreadable: scss_variables/vars.scss.
in /path/to/app/src/components/myComponent/myComponent.module.scss (line 1, column 1)

文件结构:

app
-- config
---- webpack.config.dev.js
---- paths.js
-- src
---- components
------ myComponent
-------- myComponent.jsx
-------- myComponent.module.scss
---- scss_variables
------ vars.scss

webpack.config.dev.js

  const paths = require('./paths');

  {
      test: /\.module\.scss/,
      use: [
          require.resolve('style-loader'),
          {
              loader: require.resolve('css-loader'),
              options: {
                  importLoaders: 1,
                  modules: true,
                  localIdentName: '[name]__[local]__[hash:base64:5]',
                  includePaths: [paths.appSrc]
              },
          },
          'sass-loader'
      ]
  },
  {
      test: /^((?!\.module).)*\.scss/,
      use: [
          require.resolve('style-loader'),
          {
              loader: require.resolve('css-loader'),
              options: {
                  importLoaders: 1,
                  includePaths: [paths.appSrc]
              },
          },
          'sass-loader'
      ]
  },

paths.js

const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
module.exports = { appSrc: resolveApp('src') };
reactjs webpack create-react-app sass-loader
1个回答
0
投票

使用Webpack的resolve.alias配置属性来定义导入的快捷方式位置。

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

现在@import ../../scss_variables/vars.scss可以写成@import scss_variables/vars.scss


编辑

在您的配置中使用此代替您拥有的内容:

{
  test: /\.module\.scss/,
  use: [
    'style-loader',
    {
      loader: 'css-loader',
      options: {
        importLoaders: 1,
        modules: true,
        localIdentName: '[name]__[local]__[hash:base64:5]',
        includePaths: [paths.appSrc]
      },
    },
    'sass-loader'
  ]
},
{
  test: /(?<!\.module)\.scss$/,
  use: [
    'style-loader',
    {
      loader: 'css-loader',
      options: {
        importLoaders: 1,
        includePaths: [paths.appSrc]
      },
    },
    'sass-loader'
  ]
}

它看起来像你没有前面的.scss部分的.module文件的正则表达式测试是不正确的。

© www.soinside.com 2019 - 2024. All rights reserved.