詳細介紹webpack處理CSS的執行個體

來源:互聯網
上載者:User
1、安裝外掛程式


npm i style-loader css-loader --save-devnpm i postcss-loader --save-devnpm i autoprefixer --save-devnpm install postcss-import --save-dev

style-loader外掛程式為:通過注入<style>標籤將CSS添加到DOM中

autoprefixer 自動添加首碼

postcss-import:支援使用@import引入css

2、項目目錄結構:


common.css為:

@import './flex.css';html,body{    padding: 0;    margin: 0;    background-color: red;}ul{    list-style: none;    margin: 0;}

flex.css為:


.flex-p{    display: flex;}

app.js為:


import  './css/common.css';import layer from './components/layer/layer.js'const App = function(){    console.log(layer)}new App()


3、webpack.config.js設定檔為:

var htmlWebpackPlugin = require('html-webpack-plugin');module.exports = {    entry: './src/app.js',    output: {        path: __dirname + '/dist',        filename: 'js/[name].js'    },    module: {        loaders: [{                test: /\.js$/,                                //以下目錄不處理                exclude: /node_modules/,                                //只處理以下目錄                include: /src/,                loader: "babel-loader",                                //配置的目標運行環境(environment)自動啟用需要的 babel 外掛程式                                query: {                    presets: ['latest']                }            },            //css 處理這一塊                                    {                test: /\.css$/,                use: [                                    'style-loader',                    {                        loader: 'css-loader',                        options: {                                                    //支援@important引入css                            importLoaders: 1                        }                    },                    {                        loader: 'postcss-loader',                        options: {                            plugins: function() {                                                            return [                                                                //一定要寫在require("autoprefixer")前面,否則require("autoprefixer")無效                                    require('postcss-import')(),                                    require("autoprefixer")({                                            "browsers": ["Android >= 4.1", "iOS >= 7.0", "ie >= 8"]                                    })                                ]                            }                        }                    }                ]            }        ]    },    plugins: [        new htmlWebpackPlugin({            template: 'index.html',            filename: 'index.html'        })    ]}

4、執行編譯&查看結果

npm run webpack

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.