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

时间:2018-09-12 22:08:05

标签: reactjs webpack create-react-app sass-loader

我在以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') };

1 个答案:

答案 0 :(得分: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文件进行的正则表达式测试似乎不正确。