react 项目打包后静态资源引用CDN地址

react 项目开发完毕,并成功部署访问,由于本人的服务器带宽较低。



导致访问网页速度异常过慢! 体验比较差,所以我就想把静态资源放在cdn 上。


在网上找了一圈,全是关于  homepage 相关,类似这样的


我边张homepage 加上 "http://cdn.aliyun.com/"  
运行 
yarn build

查看index.html   引用的css和js文件,还是/static/js/12323.ext.js

因为react 的脚手架是采用的create-react-app 所以我看了下react-script

const resolveApp = relativePath => path.resolve(appDirectory, relativePath);// We use `PUBLIC_URL` environment variable or "homepage" field to infer// "public path" at which the app is served.// webpack needs to know it to put the right <script> hrefs into HTML even in// single-page apps that may serve index.html for nested URLs like /todos/42.// We can't use a relative path in HTML because we don't want to load something// like /todos/42/static/js/bundle.7289d.js. We have to know the root.const publicUrlOrPath = getPublicUrlOrPath(
  process.env.NODE_ENV === 'development',
  require(resolveApp('package.json')).homepage,
  process.env.PUBLIC_URL);
   {
              loader: require.resolve('file-loader'),
              // Exclude `js` files to keep "css" loader working as it injects
              // its runtime that would otherwise be processed through "file" loader.
              // Also exclude `html` and `json` extensions so they get processed
              // by webpacks internal loaders.
              exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
              options: {
                name: 'static/media/[name].[hash:8].[ext]',
              },
            },

这上面的代码是react-script中 理解了下大致意思

  1. development 一般正常情况下这里指开发环境,就是 yarn start 环境  publicUrlorPath 公共资源的路径。
  2. 在开发环境中 读取 package.json  的homepage
  3. 如不是开发环境则读取,则读取 环境变量的  process.env.PUBLIC_URL
  4. 下面一段代码则是在编译文件时候,最终的位置是 'static/media'  这个不想vue-cli脚手架可以配置打包目录
  5. 看完这些代码,大致明白了意思!在build 的时候先设置环境变量

最后运行代码:

PUBLIC_URL=http://xinblog.oss-cn-qingdao.aliyuncs.com/react-blog/ yarn build

先设置环境变量PUBLIC_UR 打包完成,查看index.html




静态资源路径成功编程 CDN路径,在访问一下网站,super xing 访问静态资源的速度都上来了,么么搭