{"id":18255272,"url":"https://github.com/liubin915249126/react-study","last_synced_at":"2025-04-04T17:31:12.041Z","repository":{"id":25410464,"uuid":"103745200","full_name":"liubin915249126/react-study","owner":"liubin915249126","description":"webpack4.x+react+react-router+fetch+koa2+antd web 模版","archived":false,"fork":false,"pushed_at":"2024-03-18T02:58:29.000Z","size":5568,"stargazers_count":29,"open_issues_count":23,"forks_count":9,"subscribers_count":3,"default_branch":"dva","last_synced_at":"2024-04-15T15:12:09.091Z","etag":null,"topics":["javascript","koa2","nodejs","react","webpack"],"latest_commit_sha":null,"homepage":"https://liubin915249126.github.io/react","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/liubin915249126.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-09-16T10:50:36.000Z","updated_at":"2024-05-13T00:28:09.480Z","dependencies_parsed_at":"2023-01-14T03:30:22.502Z","dependency_job_id":"b282157e-49c7-4212-a4cc-0a24efee13c4","html_url":"https://github.com/liubin915249126/react-study","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liubin915249126%2Freact-study","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liubin915249126%2Freact-study/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liubin915249126%2Freact-study/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liubin915249126%2Freact-study/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/liubin915249126","download_url":"https://codeload.github.com/liubin915249126/react-study/tar.gz/refs/heads/dva","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223150662,"owners_count":17095959,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","koa2","nodejs","react","webpack"],"created_at":"2024-11-05T10:15:19.553Z","updated_at":"2024-11-05T10:15:20.343Z","avatar_url":"https://github.com/liubin915249126.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":" ## 目录说明：\n \u003e\n [webpack配置](https://github.com/liubin915249126/react-study#webpack配置)\n \u003e\n \u003e\n [安装react](https://github.com/liubin915249126/react-study#安装react)\n \u003e\n \u003e\n [使用路由](https://github.com/liubin915249126/react-study#使用路由)\n \u003e\n \u003e\n [安装-antd](https://github.com/liubin915249126/react-study#7安装-antd)\n \u003e\n \u003e\n [nodejskoa2提供后台接口](https://github.com/liubin915249126/react-study#10使用nodejskoa2提供后台接口)\n \u003e\n \u003e\n [使用fetch](https://github.com/liubin915249126/react-study#9使用新的ajax模型--fetch)\n \u003e\n\n\u003e\n技术栈：webpack3.5.6+react+react-router-dom4.0+fetch+koa2\n\n\n\u003e\n\n\n\n# webpack与react\n## webpack配置\n\n#### 0.初始化项目\n     cd 'your/path/' npm init;  \n#### 1.安装webpack\n     安装cnpm镜像\n     npm install -g cnpm --registry=https://registry.npm.taobao.org\n     全局安装：cnpm install webpack -g;\n     项目内安装：cnpm install webpack --only=dev --save;\n#### 2.配置webpack.config.js文件\n```\n     const path = require('path');\n\n     module.exports = {\n         entry: './Script/main.js', //项目入口文件\n         output:{                    //输出编译后文件地址及文件名\n             path: path.resolve(__dirname, 'dist'),\n             filename: 'bundle.js'\n         }\n     };\n```          \n命令行里面执行 webpack 命令即可看到编译后的文件\n#### 3安装webpack-html-plugin\nnpm install html-webpack-plugin --save-dev\n```\n    const HtmlWebpackPlugin = require('html-webpack-plugin');\n    ...\n    plugins:[\n        ...\n        new HtmlWebpackPlugin({\n            title:'react 学习',\n            inject:'body',\n            filename:'index.html',\n            template:path.resolve(__dirname, \"index.html\")\n        }),\n        ...\n    ]\n```          \n\u003e\n再次执行webpack命令可看到多了一个index.html文件\n这个文件是根据模板生成的并自动引入打包生成的js文件\n运行打包后的index.html即可看到效果。\n\u003e\n\n## 安装react\n#### 4.安装 react react-dom babel\n\nnpm install react react-dom --save\n\n配置laoder\n```\n...\nmodule:{\n        loaders:[\n            {\n                test: /\\.jsx$/,\n                exclude: /^node_modules$/,\n                use: [{loader:'babel-loader'}],\n                include: [APP_PATH]\n            }\n        ]\n    }\n    ...\n```\n```\n    npm install babel-preset-react --save-dev\n    npm install babel-loader babel-core babel-preset-env --save-dev\n    npm install babel-preset-stage-0 babel-preset-stage-1 babel-preset-stage-3 --save-dev\n```\n\u003e\n配置 .babelrc\n创建一个文件.babelrc。Babel是一个工具你可以转换ES6到现在的Javascript。React需要配置env和stage-0：\n\u003e\n```\n   {\n    \"presets\": [\n        \"react\",\n        \"env\",\n        \"stage-0\",\n    ]\n    ...\n}\n```\n更改main.js为main.jsx修改代码为\n```\n    import React from 'react';\n    import ReactDOM from 'react-dom';\n\n    class MainView extends React.Component{\n        constructor(props){\n            super(props)\n        }\n        render(){\n            return (\u003cdiv\u003e\n                测试\n            \u003c/div\u003e)\n        }\n    }\n    ReactDOM.render(\n        \u003cMainView/\u003e,\n        document.getElementById('main')\n\n    )\n```\n打开打包生成的页面即可看到\n打包时出错\n(npm install --save bluebird)\n![index1](https://github.com/liubin915249126/react-study/blob/master/images/index1.png)\n\n#### 5.使用webpack-dev-server\nnpm install webpack-dev-server --save-dev\n配置webpack.config.js\n```\n    ...\n    devServer: {\n        historyApiFallback: true,\n    },\n    ...\n```  \n配置package.json里面命令\n```\n    \"start\":\"webpack-dev-server --hot --inline --progress --open\"\n```\n执行 npm start 浏览器自动打开页面，更改文件后即可看到页面实时更新\n![index2](https://github.com/liubin915249126/react-study/blob/master/images/index2.png)\n\n## 使用路由\n#### 6.react-router4.2.0\n     npm install --save react-router\n     npm install --save react-router-dom\nreact-router4.0相对于之前版本变化比较大:\n\u003e\n路由配置文件：\n\u003e\n```\nconst routes =[\n    { path: '/', component: LoginView, exact:true},\n    { path: '/login', component: LoginView},\n    { path: '/main', component: Main ,routes:[\n        { path: '/main', component: Home, exact:true},\n        // { path: '/main/home', component: Home},\n        { path: '/main/about', component: About},\n        { path: '/main/timeline/:status', component: TimeLine}\n    ]}\n]\n```\n\u003e\n递归生成路由\n```\nconst RouteWithSubRoutes = (route) =\u003e (\n    route.exact?\u003cRoute path={route.path} exact render={props =\u003e (\n        \u003croute.component {...props} routes={route.routes}\u003e\n            \u003cSwitch\u003e\n            {route.routes\u0026\u0026route.routes.map((route,i)=\u003e{\n                return \u003cRouteWithSubRoutes key={i} {...route} /\u003e\n            })}\n            \u003c/Switch\u003e\n        \u003c/route.component\u003e    \n    )} /\u003e:\u003cRoute path={route.path} render={props =\u003e (\n        \u003croute.component {...props} routes={route.routes}\u003e\n           \u003cSwitch\u003e\n            {route.routes\u0026\u0026route.routes.map((route,i)=\u003e{\n                return \u003cRouteWithSubRoutes key={i} {...route} /\u003e\n            })}\n          \u003c/Switch\u003e \n        \u003c/route.component\u003e    \n    )} /\u003e\n)\n```\n\u003e\n\u003e\n加载路由：\n\u003e\n```\n     ...\n     import { Route, Link, Switch, BrowserRouter, HashRouter } from 'react-router-dom';\n     ...\n     render(){\n        return(\n             \u003cHashRouter\u003e\n                \u003cSwitch\u003e\n                {routes.map((route,i)=\u003e{\n                    return \u003cRouteWithSubRoutes key={i} {...route} /\u003e\n                })}\n                \u003c/Switch\u003e\n            \u003c/HashRouter\u003e\n        )\n    }\n\n``` \n\u003e\n BrowserRouter和HashRouter 这里遇到两个坑(坑4),使用BrowserRouter的话，子路由页面刷新的时候，\n 会加载不到打包的资源文件(加载路径变化),打包后的页面打开后是空白的。\n\u003e\n\u003e    \n参考文献[react.config](https://reacttraining.com/react-router/web/example/route-config)\n[github](https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/migrating.md)地址\n\u003e\n## 7.安装 antd\nnpm install antd --save\n按需加载组件 npm install babel-plugin-import --save-dev\n配置 .babelrc\n```\n    ...\n   \"plugins\": [[\"import\", {\n    \"libraryName\": \"antd\",\n    \"style\": true\n  }]]\n```\n#### 8.配置webpack.config.js加载less/css文件\nnpm install less-loader css-loader style-loader less --save -dev\n(坑3忘了安装less)\n参考文献[less-loader](https://github.com/webpack-contrib/less-loader)\n```{\n    test:/\\.less$/,\n    use: [{ loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'less-loader' }]\n   }\n```\n加载less文件加载组件\n```\n   ...\n   import 'antd/dist/antd.less';\n   import {DatePicker,message} from 'antd';\n   ...\n   render() {\n        return (\u003cdiv\u003e\n            \u003cDatePicker onChange={value =\u003e this.handleChange(value)} /\u003e\n        \u003c/div\u003e)\n```\n效果图![效果图](https://github.com/liubin915249126/react-study/blob/master/images/antd1.png)\n#### 9.使用新的ajax模型--fetch\n\u003e\n参照官方文档[github/fetch](https://github.com/github/fetch)\n可以自己封装一个request函数：\n\u003e\n```\n  function request(url,options){\n    return fetch(url,{\n        headers: {\n            'Accept': 'application/json',\n            'Content-Type': 'application/json'\n        },\n        credentials: 'include',\n        ...options\n    })\n        .then(checkStatus)\n        .then(parseJSON)\n        .catch(e=\u003e{\n            console.log(e)\n        })\n  }\n```\n\u003e\n在使用async await关键字时报错，安装 babel-polyfill 并引入\n参考[babel-polyfill](http://babeljs.io/docs/usage/polyfill/)\n```\n    npm install babel-polyfill --save \n``` \n\n\u003e\n## 10.使用nodejs+koa2提供后台接口\nnpm install koa koa-router --save-dev\n\u003e\n在根目录下下新建server/index.js文件index.js:\n\u003e\n```\n    const Koa = require('koa');\n    const router = require('koa-router')();\n    const app = new Koa();\n    router.get('/', (ctx, next)=\u003e {\n        ctx.response.body = '111'\n    });\n\n    app\n        .use(router.routes())\n        .use(router.allowedMethods());\n\n    app.listen(3000,()=\u003e{\n       console.log('server is start at port 3000')\n    });\n    \n```\n\u003e\npackage.json里面设置命令:\"server\":\"node server index.js\"\n启动服务:npm run server\n浏览器里面访问localhost/3000可看到返回值\n\u003e\n#### 11.设置koa允许前端跨域访问\n\u003e\n使用[koa2-cors](https://github.com/zadzbw/koa2-cors)设置跨域\n安装npm install koa2-cors --save-dev\n```\n   ...\n    app.use(cors({\n        origin: function (ctx) {\n            if (ctx.url === '/test') {\n                return false;\n            }\n            return '*';\n        },\n        exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],\n        maxAge: 5,\n        credentials: true,\n        allowMethods: ['GET', 'POST', 'DELETE'],\n        allowHeaders: ['Content-Type', 'Authorization', 'Accept'],\n    }));\n    ...\n```\n\u003e\n#### 6.分离公共代码\nwebpack配置\n```\n    module.exports = {\n        entry: {\n            main: './Script/main.js',\n            vandor:['jquery']\n        },\n        output:{\n            path: path.resolve(__dirname, 'dist'),\n            filename: '[name].[hash].bundle.js'\n        },\n        plugins:[\n            ...\n            new webpack.optimize.CommonsChunkPlugin({\n                names: [\"vandor\", \"manifest\"]\n            })\n        ]\n    }\n```\n### 路由级别的按需加载\nwebpack配置\n```\n   output:{\n        publicPath:'',\n        path: path.resolve(__dirname, 'dist'),\n        filename: 'js/[name].[hash].bundle.js',\n        chunkFilename: 'js/[name][chunkhash].js',\n    },\n```\n\u003e\n安装 react-loadable \n```\n   npm install react-loadable --save-dev\n```\n使用：\n```\n   const HomeComponent = Loadable({\n    loader: () =\u003e import('./home/HomeView'),\n    loading: LoadingPage\n    })\n    function LoadingPage(){\n        return \u003cdiv\u003eloading...\u003c/div\u003e\n    }\n```\n参考文献[github](https://github.com/thejameskyle/react-loadable)\n[github](https://github.com/thejameskyle/react-loadable-example.git)\n[react-router](https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/guides/code-splitting.md)\n\u003e\n\n#### 使用mobx\n\u003e\n安装：cnpm install mobx mobx-react --save;\n\u003e\nplugins:['transform-decorators-legacy']\nnpm install babel-plugin-transform-decorators-legacy --save-dev\n\n#### 升级webpack-v4\n```js\n    Tapable.apply is deprecated. Call apply on the plugin directly instead\n    npm install extract-text-webpack-plugin@next --save-dev\n```\n```js\n   compilation.mainTemplate.applyPluginsWaterfall is not a function\n   npm install webpack-contrib/html-webpack-plugin -D --save\n   npm install tapable --save-dev\n```\n```js\n   Cannot find module 'html-webpack-plugin'\n   \n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fliubin915249126%2Freact-study","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fliubin915249126%2Freact-study","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fliubin915249126%2Freact-study/lists"}