1. 程式人生 > >webpack 處理CSS

webpack 處理CSS

否則 dom ack .com tro html lis important common

1、安裝插件

npm i style-loader css-loader --save-dev
npm i postcss-loader --save-dev
npm i autoprefixer --save-dev
npm 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-div{
    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

技術分享

 
 

webpack 處理CSS