Webpack 是当下最热门的前端资源模块化管理和打包工具.
使用webpack 搭建react 项目(es6)
① mkdir my-demo 创建工程文件
② cd my-demo 进入工程
③创建两个文件夹 一个:app 。一个:public
④ 安装webpack
//全局安装webpack npm install -g webpack(安装过的请忽略这一步)
//安装到你的项目目录 npm install --save-dev webpack
⑤安装babel 全家桶
npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react
同时安装 react react-dom 全家桶
npm install --save-dev react react-dom
⑥app目录下创建目录components,在里面创建文件 Hello.js
import React, {Component} from 'react'
class Hello extends Component {
render() {
return (
<div>
测试一下
</div>
);
}
}
export default Hello
app目录下新建index.js
import React from 'react';
import {render} from 'react-dom';
import Hello from '../app/components/Hello';
render((
<Hello />
), document.getElementById('root'));
此处可以直接跳到下面 番外篇(略过创建index.js),安装自动生成html插件。也可按顺序。
public目录下创建index.html入口文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id='root'>
</div>
<script type="text/javascript" src="bundle.js"></script></body>
</html>
⑦ 创建一个webpack.config.js 配置如下
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: path.resolve(__dirname, './app/index.js'),
output: {
path: path.resolve(__dirname, './public'),
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.json$/,
loader: "json"
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',//在webpack的module部分的loaders里进行配置即可
query: {
presets: ['es2015','react']
}
}
]
},
};
⑧
webpack 完美运行
番外篇:
①安装插件:自动生成index. html
npm install --save-dev html-webpack-plugin
删除 public目录下的index
在app目录下创建文件 index.tmpl.html作为原型
更新webpack.config.js配置
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: path.resolve(__dirname, './app/index.js'),
output: {
path: path.resolve(__dirname, './public'),
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.json$/,
loader: "json"
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015','react']
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: __dirname + "/app/index.tmpl.html"//
})
],
};
②安装插件:实现浏览器检测代码的修改
npm install --save-dev webpack-dev-server
在package.json中添加
"scripts": {
...
"dev": "webpack-dev-server"
}
在webpack.config.js 中添加
module.exports = {
...
module: {
...
devServer: {
contentBase: "./public",//本地服务器所加载的页面所在的目录
historyApiFallback: true,//不跳转
inline: true,//实时刷新
port: 8080,//设置默认监听端口,如果省略,默认为"8080"
},
...
};
然后
npm run dev
完美