React

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > React > react打包优化和本地预览

react打包优化和本地预览的实现

作者:前端小趴菜05

本文主要介绍了react打包优化和本地预览的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

项目打包

打包指的是将项目中的源代码和资源文件进行处理,生成可在生产环境中运行的静态文件的过程

打包命令

npm run build

本地预览

本地预览是指在本地通过静态服务器模拟生产服务器运行项目的过程

安装本地服务包

npm i -g serve

启动

serve -s build

浏览器访问生成的本地地址 一般是3000端口

http://localhost:3000/

打包优化

路由懒加载

什么是路由懒加载?

路由懒加载是指路由的JS资源只有在被访问的时候才会动态获取,目的是为了优化项目首次打开的时间

配置路由懒加载

  1. 把路由修改为由React提供的lazy函数进行动态导入
  2. 使用React内置的Suspense组件包裹路由中element选项对应的组件

lazy函数进行动态导入

// 格式
const 命名 = lazy(()=>import('路径'))

const Month = lazy(()=>import('@/page/Month/index'))

 Suspense组件包裹路由组件

const router = createBrowserRouter([
  {
    path: "/",
    element: <Suspense> <Layout/></Suspense>,
    children: [
      {
        path: "/year",
        element:<Suspense><Year/></Suspense>,
      },
      {
        
        index:true,
        element: <Suspense><Month/></Suspense> ,
      },
    ],
  }
])

包体积分享

什么是包体积分析

通过可视化的方式,直观的体现项目中各种包打包之后的体积大小方便做优化

实现

安装

npm i source-map-explorer

 配置命令指定要分析的js文件

 "scripts": {
    "start": "craco start",
    "build": "craco build",
    "server": "json-server ./mock/home.json --port 3005",
    "explorer": "source-map-explorer 'build/static/js/*.js'"  //分析命令
  },

运行命令

npm run explorer

运行成功会自动在浏览器打开分析图

CDN优化

什么是CDN?

CDN是一种内容分发网络服务,当用户请求网站内容时,有离用户最近的服务器将缓存资源内容传递给用户

哪些资源可以放到CDN服务器?

体积较大的非业务JS文件,比如react,react-dom

项目中怎么实现 ?

 通过 craco 来修改 webpack 配置,从而实现 CDN 优化  

craco.config.js 中:

const path = require('path')
 
module.exports = {
  webpack:{
    alias:{
      '@':path.resolve(__dirname,'src')
    },
     configure: (webpackConfig) => {
      let cdn = {
        js: [],
        css: []
      }
      // 对webpack进行配置
      whenProd(() => {
        // 只会在生产环境执行
        webpackConfig.externals = {
          react: 'React',
          'react-dom': 'ReactDOM',
          redux: 'Redux',
        }
 
        cdn = {
          js: [
            'https://cdn.bootcdn.net/ajax/libs/react/17.0.2/umd/react.production.min.js',
            'https://cdn.bootcdn.net/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js',
            'https://cdn.bootcdn.net/ajax/libs/redux/4.1.0/redux.min.js'
          ],
          css: []
        }
      })
 
      const { isFound, match } = getPlugin(
        webpackConfig,
        pluginByName('HtmlWebpackPlugin')
      )
      if (isFound) {
        // 找到了html的插件
        match.options.cdn = cdn
      }
 
      return webpackConfig
    }
  }
}

public/index.html 中:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" rel="external nofollow"  />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" rel="external nofollow"  />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" rel="external nofollow"  />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!-- 动态插入cdn资源 -->
     <% htmlWebpackPlugin.options.cdn.css.forEach(cdnURL => { %>
      <link rel="stylesheet" href="<%= cdnURL %>" rel="external nofollow" ></link>
    <% }) %>

    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

到此这篇关于react打包优化和本地预览的实现的文章就介绍到这了,更多相关react打包优化和本地预览内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文