- 在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 ( ); }}复制代码
ReactDom.render( , 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: { // 一些loader 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" },复制代码