webpack 樣式

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文件,結合代碼分離可以有兩種方式:

  • 每個初始塊創建一個css文件,然后在別的依賴塊中引入樣式,可以優化初始化加載時間。
  • 每個初始塊創建一個css文件,同時包含了依賴塊中的樣式,更適合多入口點的小型app,因為可以利用緩存來減少http請求。(通過設置new ExtractTextPlugin("style.css", { allChunks: true })開啟)
// 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")
    ]
}

將得到以下輸出文件:

  • post.js/post.css
  • about.js/about.css
  • 1.js/2.js(包含內嵌樣式 或者 設置allChunks: true不包含內嵌樣式)

抽離公共CSS樣式

結合CommonsChunkPlugin插件可以抽離公共CSS文件。

plugins: [
    new webpack.optimize.CommonsChunkPlugin("commons", "commons.js"),
    new ExtractTextPlugin("[name].css")
]
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • GitChat技術雜談 前言 本文較長,為了節省你的閱讀時間,在文前列寫作思路如下: 什么是 webpack,它要...
    蕭玄辭閱讀 12,715評論 7 110
  • 在現在的前端開發中,前后端分離、模塊化開發、版本控制、文件合并與壓縮、mock數據等等一些原本后端的思想開始...
    Charlot閱讀 5,498評論 1 32
  • webpack 介紹 webpack 是什么 為什么引入新的打包工具 webpack 核心思想 webpack 安...
    yxsGert閱讀 6,501評論 2 71
  • 無意中看到zhangwnag大佬分享的webpack教程感覺受益匪淺,特此分享以備自己日后查看,也希望更多的人看到...
    小小字符閱讀 8,237評論 7 35
  • 你就像一場遙不可及的雨,卻讓我的心塵埃落定!
    一束陌佳閱讀 179評論 0 1