我正在使用具有此目录结构的React和Webpack构建Web应用程序
/src /components /containers App.js App.scss /assets /fonts MarkOT/ MarkOT.css MarkOT.eot ... ... /images /styles _vars.scss
我正试图从App.scss导入_vars.scss,如下所示:
@import '../../styles/vars';
这很好用.如果我在_vars.scss中有导入,那么什么是行不通的
@import "../assets/fonts/MarkOT-ExtraLight/MarkOT-ExtraLight.css"; @import "../assets/fonts/MarkOT-Light/MarkOT-Light.css"; @import "../assets/fonts/MarkOT/MarkOT.css"; @import "../assets/fonts/MarkOT-Medium/MarkOT-Medium.css"; @import "../assets/fonts/MarkOT-Book/MarkOT-Book.css";
这些导入应该相对于样式文件夹解析.而是相对于containers / App / App.scss解析导入.我在sass-loaders网站上读到,应该使用resolve-url-loader来解决这个问题,但我无法让它工作.
导入类似@import“〜../ assets / fonts / MarkOT-ExtraLight / MarkOT-ExtraLight.css”;只包含一个@ font-face声明:
@font-face { font-family: 'MarkOT'; src: url('MarkOT.eot?#iefix') format('embedded-opentype'),url('MarkOT.otf') format('opentype'),url('MarkOT.woff') format('woff'),url('MarkOT.ttf') format('truetype'),url('MarkOT.svg#MarkOT') format('svg'); font-weight: normal; font-style: normal; }
这是我的webpack配置:
var webpack = require('webpack'); var path = require('path'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { devtool: 'source-map',context: path.resolve(__dirname,'..'),entry: { app: path.resolve(__dirname,'../src/client/index.js'),vendors: ['react','react-dom','react-router'] },output: { path: path.resolve(__dirname,'../dist'),pathInfo: true,filename: 'bundle.js',css: 'main.css' },module: { preLoaders: [ { test: /\.js?$/,loader: "eslint-loader",exclude: /node_modules/ } ],loaders: [ { test: /src\/.+.js$/,exclude: /node_modules/,loader: 'babel',query: { presets: ['react','es2015','stage-0'] } },{ test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$/,loader: "file-loader" },{ test: /\.scss?$/,loader: ExtractTextPlugin.extract('style','!css?sourceMap!resolve-url!sass?outputStyle=expanded&sourceMap&includePaths[]=' + encodeURIComponent(require('node-bourbon').includePaths) + '&includePaths[]=' + encodeURIComponent(require('node-neat').includePaths[1])) } ] },resolve: { modulesDirectories: [ 'src','node_modules' ] },plugins: [ new webpack.optimize.CommonsChunkPlugin('vendors','vendors.js'),new ExtractTextPlugin('main.css') ] };
这一行尤其适合处理我的风格:
{ test: /\.scss?$/,'!css?sourceMap!resolve-url!sass?outputStyle=expanded&sourceMap&includePaths[]=' + encodeURIComponent(require('node-bourbon').includePaths) + '&includePaths[]=' + encodeURIComponent(require('node-neat').includePaths[1])) }
正如它在resolve-url-loader网站上所说,我在sass和css加载器中都包含了源映射(以及包含波旁和整齐库的路径,所有这些都加载正常).
有什么明显的东西我想念我看不到吗?
编辑:
我能够通过在与_var.scss相同的目录中创建_font.scss文件来解决该问题,将所有@ font-face声明移动到_font.scss中,然后在字体声明中替换url的所有实例.
我不喜欢我无法弄清楚为什么另一个人正在工作,但它的工作原理很好.我发现有趣的是网址不起作用,我的印象是css-loader处理了这个问题.
解决方法
在你的webpack.config中
resolve: { modulesDirectories: [ 'src','node_modules' ],alias: { styles: /*put the base folder of your styles here*/ } }
然后在样式表导入中使用@styles然后使用相对路径
@import '~styles/yourStyle.scss';