SPA 迁移到SSR_Nuxt.js 从开发到部署

首先,给自己打打气!

Let us not look back in anger, nor forward in fear, but around in awareness.

-- 不怒然回首,不恐惧前行,活着,就是现在。

补充一个关于脚手架的概念,引用自 编程中的脚手架是什么意思

这里是stackoverflow上的一个回答:

Scaffolding is a meta-programming method of building database-backed software applications. It is a technique supported by some model-view-controller frameworks, in which the programmer may write a specification that describes how the application database may be used. The compiler uses this specification to generate code that the application can use to create, read, update and delete database entries, effectively treating the template as a "scaffold" on which to build a more powerful application.

译:“脚手架”是一种元编程的方法,用于构建基于数据库的应用。许多MVC框架都有运用这种思想。程序员编写一份specification(规格说明书),来描述怎样去使用数据库;而由(脚手架的)编译器来根据这份specification生成相应的代码,进行增、删、改、查数据库的操作。我们把这种模式称为"脚手架",在脚手架上面去更高效的建造出强大的应用!

Nuxt 项目目录结构图

SPA 迁移到SSR_Nuxt.js 从开发到部署_第1张图片

1. main.css

使用 nuxt 要有意识,很多文件需要去 nuxt.config.js 这里配置才能生效。这个是原 SPA 项目的全局样式文件,迁移后是这样引入的:

// nuxt.config.js
  css: ['./assets/css/main.css'],

2. flexible.js

这是一个比较 simple 的 flexible 文件

// static/js/flexible.js
var rootResize = function() {
  var baseFontSize = 20
  var baseWidth = 5120
  var minWidth = 1920
  var clientWidth = document.documentElement.clientWidth || window.innerWidth
  var innerWidth = Math.max(Math.min(clientWidth, baseWidth), minWidth)

  var rem = clientWidth / (baseWidth / baseFontSize)
  if (innerWidth == 5120 || innerWidth == 1920) {
    rem = innerWidth / (baseWidth / baseFontSize)
  }
  document.querySelector('html').style.fontSize = rem + 'px'
}
rootResize()

window.onresize = function() {
  rootResize()
}

巨坑,我原本把 flexible 文件当做 plugin 引入了,如下,这是一个错误示范:

// nuxt.config.js
  plugins: [
    {
      src: '@/static/js/flexible.js', ssr: false
    }
  ],

这里的 ssr 一定要设置为 false, 否则会报一个叫 document is not defined 的错。倒也不是不可以生效,不过它是有一个延迟生效的问题。

!!!最优解决方案是,添加 head 配置:
// nuxt.config.js
head: {
    // title, meta, link etc.
    script: [{ src: '/js/flexible.js', type: 'text/javascript', charset: 'utf-8' }]
  },

划重点,重点,重点!!!这里的 src 路径一定要写 static 下面的绝对路径就好,也就是 /js/flexible.js but not /static/js/flexible.js

3. axios

nuxt 自带 axios "@nuxtjs/axios"

添加配置:

// nuxt.config.js
 modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
  ],
 axios: {
    proxy: true,
    prefix: '/api/',
    credentials: true
  },

  proxy: {
    '/api/': {
      target: 'http://my-api/',
      pathRewrite: {
        '^/api/': '/',
        changeOrigin: true
      }
    }
  },

以上配置都是针对 vue 文件的,所以在 vue 组件中可以使用 this.$axios 来调用。

  • 组件文件中使用:
// *.vue 
this.$axios.get('/getInfo').then((res)=>{
    console.log(res)
})
  • stats.js 等其他文件中使用:
// middleware/stats.js
import axios from 'axios'
export default function({ route }) {
  return axios.post('http://my-stats-api.com', {
    params,
  })
}

4. eventBus

// plugins/bus-inject.js
import Vue from 'vue'

export default (ctx, inject) => {
  const bus = new Vue()
  inject('bus', bus)
}

组件中触发事件:

// app.vue
this.$axios
        .get('/getData')
        .then(response => {
          let res = response.data || {}
          this.$bus.$emit('data', res)
        })
        .catch(error => {
          console.log(error)
        })

组件中接收事件:

// sub.vue
this.$bus.$on('data', (res)=>{
    console.log(res)
})

5. wordcloud echarts の词云

// plugins/echarts.js
import Vue from 'vue'
import echarts from 'echarts'
import wordCloud from 'echarts-wordcloud'

Vue.prototype.$echarts = echarts
Vue.prototype.$echarts.wordCloud = wordCloud
// nuxt.config.js
 plugins: [
 ...
    { src: '@/plugins/echarts', ssr: false }
...
  ],

同样,ssr: false 一定要写,否则会报 error: window is not defined

6. 本机 ip 访问替代 localhost

// package.json
"config": {
    "nuxt": {
      "host": "0.0.0.0",
      "port": 3000
    }
  }

7. BMap api 百度 Map 的 api key

// nuxt.config.js
head:{
    // title, meta, link etc.
  script: [
     ...
      {
        src:
          'http://api.map.baidu.com/api?v=2.0&ak=key...'
      }
      ...
    ]
}

8. iframe 的问题

这个坑是很奇怪的,在 SPA 模式开发一个项目,我会把写好的页面以 iframe 的形式串联到一起,and by then it worked well. 可是到了 SSR 莫名其妙的出现了类似线程阻塞的问题,倒是不需要纠结,只要改成组件引入即可。

出现这个问题的原因应该是,如果是 iframe 的方式引入,首先需要这个页面已经渲染完成,然后再通过 iframe 引入。所以导致了阻塞问题。

9. 打包与部署

9.1 本地打包

首先执行打包命令:

yarn build 

yarn build 之前需要将所有的 console.log 删除或注释,or else 有可能会报 console 的错而导致打包失败。

如果打包成功了,启动打包后的项目:

yarn start

本地启动没有问题就可以进行下一步了。

9.2 服务器部署

9.2.1 服务器安装 node.js,Linux 系统下安装 node.js,请移步至https://segmentfault.com/a/1190000017866964

9.2.2 服务器创建并 cd 到目录 local/deploy/front,将以下文件复制到该文件夹下:

SPA 迁移到SSR_Nuxt.js 从开发到部署_第2张图片

然后执行:

yarn install -production

成功后:

SPA 迁移到SSR_Nuxt.js 从开发到部署_第3张图片

居然还没结束,因为没有启用「进程守卫」

9.2.3 安装 pm2

安装 pm2 参考 https://www.cnblogs.com/minrh/p/9770890.html

然后 cd 到项目目录下,执行以下:

# yarn
pm2 start yarn --name "my-nuxt" -- start

# npm
pm2 start npm --name "my-nuxt" -- run start

*** 这里的 my-nuxtpackage.jsonname 的名称。

感谢那些对我们有所帮助的文章:

nuxt.js部署vue应用到服务端过程
Nuxt项目从开始到部署

你可能感兴趣的:(SPA 迁移到SSR_Nuxt.js 从开发到部署)