1. 工程配置
(1)新建工程目錄帐姻,并進(jìn)入
$ mkdir webpack-babel-react-sass && cd webpack-babel-react-sass
(2)項(xiàng)目初始化
$ npm init
會(huì)提示輸入一些工程相關(guān)的信息蝙斜,
全部使用默認(rèn)值即可箱蝠,最后會(huì)寫入到./package.json
中
(3)安裝開發(fā)環(huán)境依賴
$ npm install --save-dev \
webpack \
babel-core babel-loader babel-preset-es2015 babel-preset-react \
css-loader style-loader sass-loader node-sass \
extract-text-webpack-plugin
會(huì)自動(dòng)修改./package.json
煤杀。
其中,babel相關(guān)的有谒出,babel-core babel-loader babel-preset-es2015 babel-preset-react
隅俘,sass相關(guān)的有,css-loader style-loader sass-loader node-sass
笤喳。
extract-text-webpack-plugin
是一個(gè)webpack插件为居,用于將樣式表提取到單獨(dú)的文件中。
(4)安裝代碼依賴
$ npm install --save react react-dom
會(huì)自動(dòng)修改./package.json
(5)配置babel
新建.babelrc
文件
{
"presets": [
"es2015",
"react"
]
}
(6)配置webpack
新建webpack.config.js
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, ''),
entry: [
path.resolve(__dirname, 'src/index.jsx')
],
output: {
path: path.resolve(__dirname, 'dist/'),
filename: 'index.js'
},
module: {
loaders: [
{
test: /\.jsx$/,
loader: 'babel-loader'
},
{
test: /\.scss$/,
loaders: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
}
]
},
plugins: [
new ExtractTextPlugin('index.css')
]
};
當(dāng)前目錄結(jié)構(gòu)
+ node_modules
.babelrc
package.json
webpack.config.js
2. 示例代碼
新建component和src目錄
添加以下5個(gè)文件杀狡,
component/hello.jsx
蒙畴,component/hello.scss
,
src/index.jsx
呜象,src/index.scss
膳凝,src/index.html
,
目錄結(jié)構(gòu)如下董朝,
- component
hello.jsx
hello.scss
+ node_modules
- src
index.jsx
index.scss
.babelrc
package.json
webpack.config.js
(1)component/hello.jsx
import React, { Component } from 'react';
import './hello.scss';
class Hello extends Component {
render() {
return (
<span className="hello">hello</span>
);
}
}
export default Hello;
(2)component/hello.scss
.hello {
color:red;
}
(3)src/index.jsx
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Hello from '../component/hello.jsx';
import './index.scss';
ReactDOM.render(
<div className="page">
<Hello />
</div>,
document.getElementById('page')
);
(4)src/index.scss
.page {
font-size:20px;
}
(5)src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="../dist/index.css">
</head>
<body>
<div id="page"></div>
<script src="../dist/index.js"></script>
</body>
</html>
3. 編譯運(yùn)行
(1)編譯并監(jiān)控文件改變
$ webpack --watch