1. 工程配置
(1)新建工程目录,并进入
$ mkdir webpack-babel-react-sass && cd webpack-babel-react-sass
(2)项目初始化
$ npm init
会提示输入一些工程相关的信息,
全部使用默认值即可,最后会写入到./package.json
中
(3)安装开发环境依赖
$ 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
会自动修改./package.json
。
其中,babel相关的有,babel-core babel-loader babel-preset-es2015 babel-preset-react
,sass相关的有,css-loader style-loader sass-loader node-sass
。
extract-text-webpack-plugin
是一个webpack插件,用于将样式表提取到单独的文件中。
(4)安装代码依赖
$ npm install --save react react-dom
会自动修改./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')
]
};
当前目录结构
+ node_modules
.babelrc
package.json
webpack.config.js
2. 示例代码
新建component和src目录
添加以下5个文件,
component/hello.jsx
,component/hello.scss
,
src/index.jsx
,src/index.scss
,src/index.html
,
目录结构如下,
- 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. 编译运行
(1)编译并监控文件改变
$ webpack --watch
网友评论