Подтвердить что ты не робот

Получение вывода css с помощью webpack ExtractTextPlugin

Я пытаюсь получить 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

Любые идеи?

4b9b3361

Ответ 1

ExtractTextPlugin необходимо добавить в двух местах: в загрузчике и в качестве плагина. Вот пример, извлеченный из документации таблиц стилей.

// 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$/,
                loader: ExtractTextPlugin.extract("style-loader", "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")
    ]
}

Ответ 2

Я изменил ваши имена файлов config и как их включить на странице

   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: 'scripts/bundle.js',
    publicPath: '/scripts/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new ExtractTextPlugin('styles/styles.css', {
      publicPath: '/styles/',
      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')
    }]
  }
};

Ниже приведена страница html

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

Ответ 3

Здесь работает webpack.config.js. Я не использую те же имена каталогов, которые вы делаете, но я думаю, вы можете увидеть различия и внести необходимые изменения. Я также включаю в себя мои текущие версии модулей.

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

const config = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'bundle.js',
    publicPath: 'build/'
  },
  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.js$/
      },
      {
        loader: ExtractTextPlugin.extract({fallback: 'style-loader', use: 'css-loader'}),
        test: /\.css$/
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/,
        use: [
          {
            loader: 'url-loader',
            options: { limit: 40000 }
          },
          'image-webpack-loader?bypassOnDebug'
        ]
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({filename: 'style.css',
      allChunks: true
    })
  ]
};

module.exports = config;

//и модули:

"devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^6.4.1",
    "babel-preset-env": "^1.3.3",
    "css-loader": "^0.28.0",
    "extract-text-webpack-plugin": "^2.0.0-beta.4",
    "file-loader": "^0.11.1",
    "image-webpack-loader": "^3.3.0",
    "style-loader": "^0.16.1",
    "url-loader": "^0.5.8",
    "webpack": "^2.2.0-rc.0"
  }

Ответ 4

Используя css-loader и style-loader вместе, сначала анализирует ваш CSS, а затем превращает его в узлы стиля, которые могут быть импортированы в Webpack точно так же, как код. Я не понимаю, почему вы хотите, чтобы эти искусственные отношения были построены между вашим JavaScript и вашим CSS.

Вышеупомянутый подход снова испускает CSS в конце. Зачем ставить свой код в кругосветное путешествие? Используйте raw-loader и добавьте свой основной файл CSS в свои точки входа. Вы теряете любую проверку ошибок, выполняемую css-loader, но ваша компиляция происходит намного быстрее. Но если вы используете что-то вроде sass-loader, вы все равно получите всю проверку ошибок.