webpack樣式處理

樣式嵌入

通過使用style-loader和css-loader,webpack可以將樣式文件打包進一個js包中(javascript bundle),你可以對你的樣式進行模塊化,就像require(‘./stylesheets.css’);

安裝

npm install style-loader css-loader --save-dev

配置

以下這個示例能使用require()css:

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

使用

// in your modules just require the stylesheet
// This has the side effect that a <style>-tag is added to the DOM.
require("./stylesheet.css");

分離出css bundle

結合 extract-text-webpack-plugin,webpack在本地輸出一個css文件。
運用code spliting 我們可以用兩種模式來分離出css:
* 爲每個初始塊創建一個css文件,並將樣式表嵌入其他chunks。
* 爲每個初始塊創建一個css文件,它還包含附加塊的樣式。
推薦使用第一種模式,因爲它對於初始頁面加載時間是最佳的。在具有多個入口點的小應用程序中,由於HTTP請求開銷和緩存,第二種模式可能更好

插件安裝

npm install extract-text-webpack-plugin --save

概括

要使用插件,你需要用一個特殊的loader去標記那些要移動至css文件中的模塊。在webpack編譯中的優化階段後,插件會去檢查哪些模塊與提取相關(在一種模式中,只在一個init chunk中的),此外,模塊在原始包中重新編譯,並替換爲空模塊。

樣式從初始塊到單獨的css輸出文件

此示例顯示多個入口點,但也適用於單個入口點。

// 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")
    ]
}

你將會的到如下輸出文件:
* posts.js posts.css
* post.js post.css
* about.js about.css
* 1.js 2.js (含有嵌入的樣式)

所有樣式都在單獨的css輸出文件中

要使用第二種模式,您只需要將allChunks選項設置爲true:

// ...
module.exports = {
    // ...
    plugins: [
        new ExtractTextPlugin("style.css", {
            allChunks: true
        })
    ]
}

得到如下輸出文件:
* posts.js posts.css
* post.js post.css
* about.js about.css
* 1.js 2.js (不含有嵌入的樣式)

公用塊中的樣式

您可以使用單獨的css文件與CommonsChunkPlugin結合使用。在這種情況下,也會發出公共塊的css文件。

// ...
module.exports = {
    // ...
    plugins: [
        new webpack.optimize.CommonsChunkPlugin("commons", "commons.js"),
        new ExtractTextPlugin("[name].css")
    ]
}

得到如下輸出文件:
* commons.js commons.css
* posts.js posts.css
* post.js post.css
* about.js about.css
* 1.js 2.js (contain embedded styles)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章