webpack

webpack 样式

2016-04-25  本文已影响1592人  齐修_qixiuss

css文件对于webpack来说和普通模块没有任何区别。通过style-loader和css-loader可以对css文件做解析,实现css模块化。

内嵌的CSS【不推荐使用】

webpack默认是将css直接注入到html中,这种方法并不具有通用性,不推荐使用(百度首页采用的就是讲css注入到html,但我还是不推荐使用,除非是超级简单的网页或者对速度有极致要求的网页)
webpack.config.js 代码如下:

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

独立的CSS

结合使用extract-text-webpack-plugin,可以生成一个独立的css文件,结合代码分离可以有两种方式:

// webpack.config.js
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
    // The standard entry point and output config
    entry: {
        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")
    ]
}

将得到以下输出文件:

抽离公共CSS样式

结合CommonsChunkPlugin插件可以抽离公共CSS文件。

plugins: [
    new webpack.optimize.CommonsChunkPlugin("commons", "commons.js"),
    new ExtractTextPlugin("[name].css")
]
上一篇 下一篇

猜你喜欢

热点阅读