- 在github上创建项目然后克隆到本地;
- 从命令行进入该目录对项目进行初始化
npm init -y,会自动生成一个package.json文件; - 远程安装
React最基本的依赖包npm i -S react react-dom; - 创建本地项目的入口目录
./src; - 在
./src里面创建index.html app.js文件 - 在
app.js里面写一个组件
import React, { Component } from 'react';
import ReactDom from 'react-dom';
import './index.css';
class Hello extends Component {
render() {
return (
<div className="title">Hello World!!</div>
);
}
}
复制代码
ReactDom.render(
<div>
<Hello />
</div>,
document.querySelector('#root')
);
复制代码
- 至此已经完成了react相关的创建,但现在还不能让浏览器运行,需要使用打包工具进行打包输出。
- 安装
webpack v3版本和一些webpack常用的插件npm i -D webpack@v3 babel-loader babel-core babel-preset-react babel-preset-env style-loader css-loader html-webpack-plugin clean-webpack-plugin extract-text-webpack-plugin; - 至少要安装的依赖包
"dependencies": {
"react": "^16.4.1",
"react-dom": "^16.4.1"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^0.1.19",
"extract-text-webpack-plugin": "^3.0.2",
"html-webpack-plugin": "^3.2.0",
"css-loader": "^0.28.11",
"style-loader": "^0.21.0",
"webpack": "^3.12.0"
}
复制代码
- 创建文件
./webpack.config.js;
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const extractTextPlugin = require('extract-text-webpack-plugin');
const extract_index = new extractTextPlugin({
filename: "index.css"
})
module.exports = {
entry: {
app: './src/app.js'
},
output: {
path: path.resolve(__dirname, 'build/'),
filename: '[name].js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: 'babel-loader'
},
include: [
path.resolve(__dirname, "src")
]
},
{
test: /\.css$/,
use: extract_index.extract({
fallback: "style-loader",
use: [{
loader: "css-loader",
options: {
modules: false,
}
}]
}),
include: [
path.resolve(__dirname, "src")
]
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
drop_debugger: true,
drop_console: true
}
}),
new CleanWebpackPlugin(
['build'],
{
root: __dirname
}
),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, './src/index.html')
}),
extract_index
]
}
复制代码
- 最后在命令行执行命令打包
npm run build;
注意build命令是在package.json里的script字段中定义的
"scripts": {
"build": "webpack"
},
复制代码