2017-05-27 23 views
0

我正在使用Webpack 2.5.1,React 15.5.4Webpack sass-loader無法編譯導入到反應jsx文檔中的sass樣式表:意外字符'@'

我試圖在反應項目中使用Bootstrap_utilities.scss。並且 當我嘗試編譯文檔時,Webpack報告錯誤,因爲它使用@import語句導入其他sass部分。

這是我的條目main.jsx文件的代碼。

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import 'bootstrap/scss/_utilities.scss' // this is what causes the error 
import '../stylesheets/components/gallery.scss'; // this one compiles properly if I comment the _utilities.scss import statement. It does not use @import notation. 

class Gallery extends React.Component { 
    render(){ 
    return (<div id="gallery" className="d-flex p-2"> 
      <h1>using bootstrap flex-box</h1> 
      <p>Something something something!</p> 
      <button onClick={() => console.info('You clicked a button')}>Click Me!</button> 
     </div>) 
    } 
} 

這是我的webpack.config.js的代碼。

const path = require('path'); 
const webpack = require('webpack'); 
const CommonChunkPlugin = 
require('./node_modules/webpack/lib/optimize/CommonsChunkPlugin'); 

module.exports = { 
    target: 'web', 
    watch: true, 
    devtool: 'source-map', 

    entry: { 
     main: './components/main.jsx', 
     vendor: ['react', 'react-dom'] 
    }, 

    output: { 
     path: path.resolve('..', 'build', 'js'), 
     filename: '[name].js' 
    }, 

    module: { 
     rules: [ 
      { 
       test: /\.(css|scss)$/, 
       exclude: /(node_modules)/, 
       use: [ 
        { 
         loader: 'style-loader' 
        }, 
        { 
         loader: 'css-loader', 
         options: { sourceMap: true } 
        }, 
        { 
         loader: 'sass-loader', 
         options: { sourceMap: true } 
        } 
       ] 
      }, 
      { 
       test: /(\.js|\.jsx)$/, 
       exclude: /(node_modules)/, 
       loader: 'babel-loader?cacheDirectory=true', 
       options: { 
        presets: ['es2015', 'react'] 
       } 
      } 
     ] 
    }, 

    plugins: [ 
     new CommonChunkPlugin({ 
      name: 'vendor', 
      filename: 'vendor.js' 
     }) 
    ] 
}; 

正如你所看到的,我使用style-loadercss-loadersass-loader編譯cssscss文件。

這是運行Webpack後得到的錯誤消息。

... _utilities.scss Unexpected character '@' (1:0) 
You may need an appropriate loader to handle this file type. 
| @import "utilities/align"; 
| @import "utilities/background"; ... 

我已經看到了這post而這個其他post,但他們不幫助。

那麼,有什麼我做錯了嗎?我怎樣才能解決這個問題?謝謝。

回答

0

你不包括node_modules目錄作爲SASS/CSS加載器的目標,因此Webpack將無法爲其中包含的任何SASS文件找到適當的加載器。

嘗試從SASS/CSS加載器設置中刪除exclude屬性。

0

你需要這個插件

var ExtractTextPlugin = require("extract-text-webpack-plugin"); 
var extractPlugin = new ExtractTextPlugin({ 
    filename: "main.css" 
}); 

,然後簡單地只是把

{ 
    test: /\.scss$/, 
    use: extractPlugin.extract({ 
     use: ["css-loader","sass-loader"] 
    }) 
} 

然後在插件,你需要這樣的:

plugins:[extractPlugin] 

希望它可以幫助

+0

謝謝。我試過了,但沒有奏效。 – blaze

+0

我用@toomuchdesign答案解決了它。 – blaze

相關問題