Webpack 解析css
css-loader: 加载css对象,并转换成commonjs对象
style-loader: 将样式写入style标签并插入到header中
- 安装loader
npm i style-loader@0.23.1 css-loader@2.1.1 -D
- 配置webpack
loader是一个函数
同一个loader里面,不同的use从以compose(组合)方式从右到左执行(与之对应的是pipe管道流,从左到右执行)
'use strict';
const path = require('path');
module.exports = {
// 入口 指定入口文件
entry: {
reactComp:'./src/react-comp.js'
},
// 出口
output: {
// 指定输出目录
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
// 配置babel解析ES6
module:{
rules:[
{
test:/.js$/,
use:'babel-loader'
},
{
test:/.css$/,
use:[
'style-loader', // 再将样式插入到style标签中
'css-loader' // 先将css转换成commonjs
]
}
]
},
// 生成模式还是开发模式
mode: 'production'
};
- 组件引入样式
"use strict"
import React from 'react'
import ReactDOM from 'react-dom'
import './react-comp.css'
class Search extends React.Component{
render(){
return (
<div className='search-text'>search text</div>
)
}
}
ReactDOM.render(<Search />,document.getElementById('root'))
- 打包
npm run build
- 引入打包后的文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script src="./reactComp.js" type="text/javascript"></script>
</body>
</html>
Webpack 解析less
在以上解析css的loader的基础上再加一个loader - less-loader
less-loader用于将less文件编译成css文件
再调用css-loader将css文件编译成commonjs形式
最后调用style-loader将样式写入style标签注入到header标签中
- 安装loader
npm i less-loader@5.0.0 less@3.9.0 -D
- 配置webpack
'use strict';
const path = require('path');
module.exports = {
// 入口 指定入口文件
entry: {
reactComp:'./src/react-comp.js'
},
// 出口
output: {
// 指定输出目录
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
// 配置babel解析ES6
module:{
rules:[
{
test:/.js$/,
use:'babel-loader'
},
{
test:/.less$/,
use:[
'style-loader', // 再将样式插入到style标签中
'css-loader', // 将css转换成commonjs
'less-loader' // 将less文件转换成css文件
]
}
]
},
// 生成模式还是开发模式
mode: 'production'
};
- 组件引入less并打包
"use strict"
import React from 'react'
import ReactDOM from 'react-dom'
import './react-comp.less'
class Search extends React.Component{
render(){
return (
<div className='search-text'>search text</div>
)
}
}
ReactDOM.render(<Search />,document.getElementById('root'))
相关版本文件
package.json
{
"name": "02beginning",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"build": " webpack "
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.4.4",
"@babel/preset-env": "^7.4.4",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.1",
"file-loader": "^3.0.1",
"less": "^3.9.0",
"less-loader": "^5.0.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"style-loader": "^0.23.1",
"url-loader": "^1.1.2",
"webpack": "^4.31.0",
"webpack-cli": "^3.3.2"
}
}
.babelrc
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}