2017-03-18 74 views
0

如何在生產中使用CSS模塊並在生產中加載標準css文件?使用webpack和React配置開發/生產CSS模塊

我配置與使用反應的WebPack

發展一個新的應用程序使用我的WebPack裝載機使用CSS模塊:

到我.jsx文件I導入樣式文件:

import style from './stile.scss'; 
export class App extends React.Component { 
render() { 
    return (
     <div> 
      <div> 
       <span className={style.title}>Ciao</span> 
      </div> 
     </div> 
    ) 
} 
} 

然後我對我的樣式表使用以下webpack配置加載器:

loaders: [ 
{ 
    test: /\.(scss|css)$/, 
    loader: 'style-loader!css-loader?sourceMap&modules&importLoaders=1&localIdentName=[name]-[local]___[hash:base64:5]!sass-loader?sourceMap' 
    } 
] 

這樣一切工作(包括在.js文件和類樣式正確hased)

生產?我應該讓瀏覽器呈現webpack bundle.js輸出文件中包含的所有類?

我寧願用我所有的風格創建的WebPack(和ExtracttextPlugin)一個CSS文件:

{ 
    test: /\.(css|scss)$/, 
    loader: ExtractTextPlugin.extract('css-loader') 
} 

和鏈接在我的index.html產生的.css

問題是,現在我所有的類定義納入React組件不再在瀏覽器中呈現。

我應該如何解決這個問題?

回答

1

你不能從使用CSS模塊切換到不使用它們,因爲你的代碼依賴它。也沒有理由不在生產中使用CSS模塊。你想改變的不是CSS模塊,而是你包含CSS的方式。您可以使用extract-text-webpack-plugin將它們提取到單獨的.css文件中,而不是將它們放入JavaScript包中,但仍需要對加載程序使用相同的配置。

的WebPack 1

{ 
    test: /\.(css|scss)$/, 
    loader: ExtractTextPlugin.extract('style-loader', 'css-loader?sourceMap&modules&importLoaders=1&localIdentName=[name]-[local]___[hash:base64:5]!sass-loader?sourceMap') 
} 

第一個參數style-loader只用作回退如果CSS不能被提取。

的WebPack 2

ExtractTextPlugin.extract改變的參數和使用可讀性options代替字符串中的內聯的查詢。

{ 
    test: /\.(css|scss)$/, 
    loader: ExtractTextPlugin.extract({ 
    fallback: 'style-loader', 
    use: [ 
     { 
     loader: 'css-loader', 
     options: { 
      sourceMap: true, 
      modules: true, 
      importLoaders: 1, 
      localIdentName: '[name]-[local]___[hash:base64:5]' 
     } 
     }, 
     { loader: 'sass-loader', options: { sourceMap: true } } 
    ] 
    }) 
} 
相關問題