简体   繁体   中英

Basic Webpack ExtractTextWebpackPlugin configuration

I have a problem configuring ExtractTextWebpackPlugin for simpy including separate CSS files in my HTML head tag (using link tag), which is its main purpose i believe.

My current configuration in webpack.config.js :

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

module.exports = {
  entry: './app/index.js',
  output: {
    filename: "app.js",
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('general.css')
  ]
};

In my main index.js file i have require("../style.css");

style.css is placed in project root folder.

In my index.html i have <script src="dist/app.js"></script>

As i understand this should inlclude general.css in my head tag at runtime but it is not there.

Any help is appreciated.

The ExtractTextPlugin only removes the CSS from your bundle to decouple it from the JavaScript and you need to include it in your HTML, as well as the bundle.

You can automate this by letting webpack generate an HTML file for you. That is especially useful when you use hashes in your file names. You'll need to use the html-webpack-plugin which will automatically include the bundled JavaScript as well as the CSS extracted by the ExtractTextPlugin .

Additionally, you should understand that your idea of including the CSS at runtime would negatively affect the load time of your page, because you would first need to download the JavaScript bundle (1st network request) then you would need to execute the JS, which takes some time to be parsed, and after that you'll have to download your CSS file (2nd network request). Since you depend on the bundle to be executed first, you will display your page without CSS for a brief moment, or a substantial amount of time on a low end mobile device with a bad network connection.

This is basically what happens if you don't use the ExtractTextPlugin and instead use the style-loader . The style-loader simply injects your CSS into a <style> tag, which is done from your JavaScript bundle, so it still depends on the bundle being executed but at least it doesn't need an extra network request for the CSS. That is even better than what you expected ExtractTextPlugin to do, which would effectively make the plugin useless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM