使用webpack ExtractTextPlugin获取css输出

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

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

这里是我的webpack配置:

var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  devtool: 'eval',entry: [
    'webpack-dev-server/client?http://localhost:3000','webpack/hot/only-dev-server','./scripts/index'
  ],output: {
    path: path.join(__dirname,'build'),filename: 'bundle.js',publicPath: '/scripts/'
  },plugins: [
    new webpack.HotModuleReplacementPlugin(),new webpack.NoErrorsPlugin(),new ExtractTextPlugin('styles/styles.css',{
      allChunks: true
    })
  ],resolve: {
    extensions: ['','.js','.jsx']
  },module: {
    loaders: [{
      test: /\.jsx?$/,loaders: ['react-hot','babel'],include: path.join(__dirname,'scripts')
    },{
        test: /\.css$/,loader: ExtractTextPlugin.extract('style-loader','css-loader')
    }]
  }
};

index.js:

import React from 'react';
import App from './App';

React.render(<App />,document.getElementById('root'));

App.js:

import React from 'react';

require('../styles/app.css');

export default class App extends React.Component {
  render() {
    return (
      <h1>Hello,world.</h1>
    );
  }
}

index.html:

<html>
  <head>
    <link rel="stylesheet" href="/styles/styles.css">
  </head>
  <body>
    <div id='root'></div>
  </body>
  <script src="/scripts/bundle.js"></script>
</html>

styles.css返回404

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

module: {
        loaders: [
            { test: /\.css$/,loader: "style-loader!css-loader" }
        ]
    }

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

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

有任何想法吗?

解决方法

ExtractTextPlugin需要在两个地方添加:在加载程序和作为插件。这里是从 stylesheets documentation拉出的例子。
// webpack.config.js
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
    // The standard entry point and output config
    entry: {
        posts: "./posts",post: "./post",about: "./about"
    },output: {
        filename: "[name].js",chunkFilename: "[id].js"
    },module: {
        loaders: [
            // Extract css files
            {
                test: /\.css$/,loader: ExtractTextPlugin.extract("style-loader","css-loader")
            },// Optionally extract less files
            // or any other compile-to-css language
            {
                test: /\.less$/,"css-loader!less-loader")
            }
            // You could also use other loaders the same way. I. e. the autoprefixer-loader
        ]
    },// Use the plugin to specify the resulting filename (and add needed behavior to the compiler)
    plugins: [
        new ExtractTextPlugin("[name].css")
    ]
}
原文链接:https://www.f2er.com/css/220959.html

猜你在找的CSS相关文章