使用webpack ExtractTextPlugin获取css输出

前端之家收集整理的这篇文章主要介绍了使用webpack ExtractTextPlugin获取css输出前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图得到css要求在webpack使用ExtractTextPlugin工作,但没有成功

我想要一个单独的CSS文件,而不是内联任何CSS。

这里是我的webpack配置:

  1. var path = require('path');
  2. var webpack = require('webpack');
  3. var ExtractTextPlugin = require('extract-text-webpack-plugin');
  4.  
  5. module.exports = {
  6. devtool: 'eval',entry: [
  7. 'webpack-dev-server/client?http://localhost:3000','webpack/hot/only-dev-server','./scripts/index'
  8. ],output: {
  9. path: path.join(__dirname,'build'),filename: 'bundle.js',publicPath: '/scripts/'
  10. },plugins: [
  11. new webpack.HotModuleReplacementPlugin(),new webpack.NoErrorsPlugin(),new ExtractTextPlugin('styles/styles.css',{
  12. allChunks: true
  13. })
  14. ],resolve: {
  15. extensions: ['','.js','.jsx']
  16. },module: {
  17. loaders: [{
  18. test: /\.jsx?$/,loaders: ['react-hot','babel'],include: path.join(__dirname,'scripts')
  19. },{
  20. test: /\.css$/,loader: ExtractTextPlugin.extract('style-loader','css-loader')
  21. }]
  22. }
  23. };

index.js:

  1. import React from 'react';
  2. import App from './App';
  3.  
  4. React.render(<App />,document.getElementById('root'));

App.js:

  1. import React from 'react';
  2.  
  3. require('../styles/app.css');
  4.  
  5. export default class App extends React.Component {
  6. render() {
  7. return (
  8. <h1>Hello,world.</h1>
  9. );
  10. }
  11. }

index.html:

  1. <html>
  2. <head>
  3. <link rel="stylesheet" href="/styles/styles.css">
  4. </head>
  5. <body>
  6. <div id='root'></div>
  7. </body>
  8. <script src="/scripts/bundle.js"></script>
  9. </html>

styles.css返回404

任何想法这里可能会出错。如果我不使用ExtractTextPlugin,只需在config中这样做:

  1. module: {
  2. loaders: [
  3. { test: /\.css$/,loader: "style-loader!css-loader" }
  4. ]
  5. }

然后我得到的CSS应用于页面正确,但显然这不是来自一个CSS文件

这是我第一次尝试使用webpack,所以可能做一些noob错误

有任何想法吗?

解决方法

ExtractTextPlugin需要在两个地方添加:在加载程序和作为插件。这里是从 stylesheets documentation拉出的例子。
  1. // webpack.config.js
  2. var ExtractTextPlugin = require("extract-text-webpack-plugin");
  3. module.exports = {
  4. // The standard entry point and output config
  5. entry: {
  6. posts: "./posts",post: "./post",about: "./about"
  7. },output: {
  8. filename: "[name].js",chunkFilename: "[id].js"
  9. },module: {
  10. loaders: [
  11. // Extract css files
  12. {
  13. test: /\.css$/,loader: ExtractTextPlugin.extract("style-loader","css-loader")
  14. },// Optionally extract less files
  15. // or any other compile-to-css language
  16. {
  17. test: /\.less$/,"css-loader!less-loader")
  18. }
  19. // You could also use other loaders the same way. I. e. the autoprefixer-loader
  20. ]
  21. },// Use the plugin to specify the resulting filename (and add needed behavior to the compiler)
  22. plugins: [
  23. new ExtractTextPlugin("[name].css")
  24. ]
  25. }

猜你在找的CSS相关文章