2.webpack入门使用loader处理css

2.webpack入门使用loader处理css

首先上代码

  1. 新建main.css
    win创建文件命令
type > main.css

修改内容为

#app {
    background: red;
    color: rgb(26, 4, 122);
}
  1. 修改app.js引入css
import { show } from './test' 
require('./main.css')
show (' world')

  1. 修改webpack.config.js
const path= require ('path')
module.exports = {
    entry:'./app.js', 
    output: {
    filename:'bundle.js',
    path: path.resolve( __dirname,'dist')
    },
    module:{
        rules:[
            {
                test:/\.css$/,
                use: ['style-loader', 'css-loader'], 
            }
        ]
    }
}

module是使用loader部分,注意引用顺序'style-loader', 'css-loader'
test 是匹配的文件正则
use 属性的值需要是一个由 Loader 名称组成的数组, Loader 的执行顺序是由后到前的

  1. 最后安装 css-loader style-loader
npm install css-loader style-loader -S -D

npm run build 一下完美结束

  1. 目录结构
    demo1.1
        --index.html
        --app.js
        --test.js
        --main.css
        --webpack.config.js
        --package.json
  1. 最后附上各文件代码
    index.html


       
     

app.js

import { show } from './test' 
require('./main.css')
show (' world')

test.js

export const show = function (content) {
    window.document.getElementById ('app') .innerText = 'Hello1' + content
}

main.css

#app {
    background: red;
    color: rgb(26, 4, 122);
}

webpack.config.js

const path= require ('path')
module.exports = {
    entry:'./app.js', 
    output: {
    filename:'bundle.js',
    path: path.resolve( __dirname,'dist')
    },
    module:{
        rules:[
            {
                test:/\.css$/,
                use: ['style-loader', 'css-loader'], 
            }
        ]
    }
}

package.json

{
  "name": "demo1.1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --config ./webpack.config.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^4.2.2",
    "style-loader": "^1.2.1",
    "webpack": "^4.44.1",
    "webpack-cli": "^3.3.12"
  },
  "dependencies": {}
}

上一篇 1.超简单的webpack入门demo
下一篇 3. webpage4.0 mini-css-extract-plugin插件简单介绍

你可能感兴趣的:(2.webpack入门使用loader处理css)