我在webpack 3.10.0
开始的React项目中使用create-react-app
。我正在尝试调整我的Webpack配置,以便我可以导入没有相对路径的scss文件。
例如@import ../../scss_variables/vars.scss
在myComponent.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') };
使用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
文件的正则表达式测试是不正确的。