使用nginx部署react项目 |
您所在的位置:网站首页 › react怎么运行项目 › 使用nginx部署react项目 |
一、环境准备 1.安装node和yarn 开始部署react前需要安装node和yarn,可以参考这里安装node和yarn。 2.安装nginx ubuntu安装nginx,windows安装nginx,源码安装nginx 二、部署构建Reat项目1.下载源代码并解压 123wget https://github.com/mdnice/markdown-nice/archive/master.zipunzip master.zipcd markdown-nice-master/2. 进入源码目录并安装 $ yarn 3.本地开发模式(可选) 在开发模式下运行应用程序。 打开 http://localhost:3000 在浏览器中查看它。 如果你更改代码,页面将自动重新加载。 你将在控制台中看到构建错误和 lint 警告。 CTRL+C退出。 $ yarn start 4. 构建发布 将 React 正确地打包为生产模式中并优化构建以获得最佳性能。 $ yarn build 1234567891011121314151617181920212223242526272829303132 [root@VM_0_16_centos markdown]# yarn build yarn run v1.22.4 $ node --max_old_space_size=4096 scripts/build.js Creating an optimized production build... Compiled successfully. File sizes after gzip: 1.84 MB build/static/js/7.99620bc9.chunk.js ... 355 B build/static/js/42.75f09c5c.chunk.js The bundle size is significantly larger than recommended. Consider reducing it with code splitting: https://goo.gl/9VhYWB You can also analyze the project dependencies: https://goo.gl/LeUzfb The project was built assuming it is hosted at https://markdown.com.cn. You can control this with the homepage field in your package.json. The build folder is ready to be deployed. You may serve it with a static server: yarn global add serve serve -s build Find out more about deployment here: https://bit.ly/CRA-deploy Done in 32.64s.构建之后会生成build目录,目录里包含项目静态的文件,如何发布这些静态文件有两种方式: 部署到nginx。 Node环境使用serve也可以运行静态文件。三、发布静态文件1.Nginx部署React 创建nginx的配置文件,并加入配置 vi /usr/local/nginx/conf/vhost/markdown.conf 12345678server { server_name markdown.com.cn; root /home/markdown/build; index index.html index.htm; location / { try_files $uri /index.html =404; }}server_name 配置你的ip或域名root 配置为build出来的静态文件路径index 入口文件 测试nginx的配置文件 nginx -t 加载配置生效 nginx -s reload 打开浏览器,访问 https://makrdown.com.cn 查看效果了 markdown排版。 2. 使用server运行 123yarn global add serveserve -s build#这样就将前端文件进行了编译,此时会在5000端口开启一个服务。四、排错1. nginx部署的react加载缓慢的问题 可以使用gzip压缩,减少网络传,在配置文件中加入 123456gzip on;gzip_buffers 32 4k;gzip_comp_level 6;gzip_min_length 200;gzip_types text/css text/xml application/javascript;gzip_vary on;2. React打包文件大的问题 如果已经开了压缩还是传输慢,检查文件体积达到几M。
![]() 修改nginx的压缩级别,调整为6,gzip_comp_level 6; ,可以减少300k。 ![]() 3. 使cdn |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |