最近须要作一个前端网站,多个页面,有搜索。决定使用react,虽然之前也用过react作过管理后台,可是从0开始建站仍是第一次,中间遇到了许多问题和各类坑,最终能够算是还算圆满的解决了。如下记录主要操做过程,大量参考了网上查找到的各类资料。javascript
安装npmphp
$ brew install node
配置cnpmcss
$ npm install -g cnpm --registry=https://registry.npm.taobao.org $ npm config set registry https://registry.npm.taobao.org
安装create-react-apphtml
$ cnpm install -g create-react-app
$ create-react-app my-app
进入项目目录前端
$ cd my-app/
根据需求,大体须要安装路由、less、ajax、代理等支持软件java
$ cnpm install react-router-dom --save $ cnpm install history --save
若是使用createBrowserHistory的话,代码编译后上传到nginx环境,须要在配置中增长如下内容node
location / { try_files $uri /index.html; }
$ cnpm install less less-loader --save-dev $ npm run eject
最后一步是将项目配置文件暴露出来,react要支持less必需要修改config/webpack.config.jsreact
打开 config/webpack.config.js,有三个地方要修改webpack
一、找到nginx
const sassModuleRegex = /\.module\.(scss|sass)$/;
在后面添加
const lessRegex = /\.less$/; const lessModuleRegex = /\.module\.less$/;
二、找到
if (preProcessor) {
整块改为
if (preProcessor) { if(preProcessor === 'less-loader') { loaders.push({ loader: require.resolve(preProcessor), options: { sourceMap: isEnvProduction && shouldUseSourceMap, javascriptEnabled: true, }, }); }else{ loaders.push({ loader: require.resolve(preProcessor), options: { sourceMap: isEnvProduction && shouldUseSourceMap, }, }); } }
三、找到 test: sassModuleRegex,
开头的对象,在后面增长
{ test: lessRegex, exclude: lessModuleRegex, use: getStyleLoaders( { importLoaders: 2, sourceMap: isEnvProduction && shouldUseSourceMap, }, 'less-loader' ), sideEffects: true, }, { test: lessModuleRegex, use: getStyleLoaders( { importLoaders: 2, sourceMap: isEnvProduction && shouldUseSourceMap, modules: true, getLocalIdent: getCSSModuleLocalIdent, }, 'less-loader' ), },
$ cnpm install whatwg-fetch --save
$ cnpm install http-proxy-middleware --save
新建文件 src/setupProxy.js
const proxy = require('http-proxy-middleware'); module.exports = app => { app.use( proxy('/api', { target: 'http://localhost/api/index.php/', changeOrigin: true, pathRewrite: { '^/api': '', }, }) ); };
效果是前端 fetch('/api/web/list')
实际指向的是:http://localhost/api/index.ph...
$ npm start
基本的安装和配置差很少就是这些了,接下来就是个人强项了,开始码代码