如何在自己的电脑上线项目?

179 阅读2分钟

1.项目打包

法1:在终端运行生产环境 yarn build:prod(可以在 package.json 里面自定义),加上 --report ,会生成打包文件 dist ,同时生成一份打包报告,我们可以根据打包报告对项目进行打包优化

image.png

image.png

法2:在终端输入 vue ui ,便会回跳到 【Beta】页面,运行开发环境或生产环境,即可生成 dist 文件,也可以看到更清晰的打包结果,然后去进行优化,再打包

image.png

image.png

2.项目打包优化概括:

  • 路由懒加载
  • 组件懒加载
  • 图片懒加载
  • 魔法注释
  • CDN
  • 减少发请求次数
  • 减少重绘和重排
  • 防抖和节流
  • 去掉console.log

3.项目上线

  • 找一处风水宝地,创建一个文件,把 dist文件放进去
  • 创建 app.js 我们需要搭建一个小型服务器

image.png

app.js 里面: hash 模式

// hash 模式
// 初始化 npm init -y
// 下包 npm  i  koa
// npm i koa-static
// npm i koa2-proxy-middleware

const Koa =require('koa')
const serve=require('koa-static')

// 解决跨域(hash 和 history 都需要)
const proxy = require('koa2-proxy-middleware')
const app=new Koa()
app.use(proxy({
    targets: {
      '/api/(.*)': {
          target: '这里放后端服务器地址', 
          changeOrigin: true
      }
    }
  }))
  
//静态化
app.use(serve(__dirname+"/dist"))
//开启服务器
app.listen(3333,()=>{
   console.log('http://127.0.0.1:3333')
  //  console.log('http://localhost:3333')//
})

// 最后在 终端 node .\app.js ,点击链接即可进入页面

app.js 里面: history 模式

// history 模式
// 初始化 npm init -y
// 下包 npm  i  koa
// npm i koa-static
// npm i koa2-connect-history-api-fallback
// npm i koa2-proxy-middleware

const Koa = require('koa')
const serve = require('koa-static')
const { historyApiFallback } = require('koa2-connect-history-api-fallback');
const proxy = require('koa2-proxy-middleware')
const app = new Koa()

app.use(proxy({
  targets: {
    '/api/(.*)': {
      target: '这里放后端后端服务器地址',
      changeOrigin: true
    }
  }
}))

// 这句话 的意思是除接口之外所有的请求都发送给了 index.html
// 这里的whiteList是 白名单的意思
app.use(historyApiFallback({
  whiteList: ['/api']
})); 

//  __dirname 当前文件夹的绝对路径
//  __filename 当前文件的完整路径

//静态化
app.use(serve(__dirname + "/dist"))

//开启服务器
app.listen(3333, () => {
  console.log('http://127.0.0.1:3333')
})

// 最后在 终端 node .\app.js ,点击链接即可进入页面

4.路由模式总结(补充了解)

hash 模式

image.png

  • hash 模式:使用 URL 的 hash 来模拟一个完整的 URL ,其显示的网络路径中带有 #
  • hash 虽然出现在 URL 中,但是不会包含在 http 请求中,对后端完全没有影响,因此改变 hash 后刷新,也不会有问题
  • 原理:hashChange事件 history 模式

image.png

  • history 模式:美化后的 hash 模式,路径中不包含 # ,依赖于 HTML5history api
  • history 刷新有白屏,由于改变了地址,刷新时会按照修改后的地址请求后端,需要后端配置处理,将地址访问做映射,否则会 404
  • 原理:popState()pushState()