• 简陋的vue-cli项目改写成nuxt2项目



    这个项目之前也是想用nuxt做的,但是当时还不会,就用了预渲染,最近刚学了nuxt,顺便练习一下
    原项目是基于 vue^2.6.11vue-cli^4.5.0开发的

    纯粹记录一下步骤以及遇到的问题

    (由于源码不能公开,已省略部分细节

    1. 安装下载nuxtjs

    npx create-nuxt-app就可以了

    或者
    我自己是手动建的:

    // 新建根目录
    mkdir project-name
    cd project-name
    
    // 新建package.json
    touch package.json
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    // package.json
    {
      "name": "project-name",
      "scripts": {
        "dev": "nuxt"
          "dev": "nuxt",
          "build": "nuxt build",
          "generate": "nuxt generate",
          "start": "nuxt start"
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    安装nuxtnpm i nuxt


    2. 配置路由

    安装:
    npm i @nuxtjs/router -S
    nuxt.config.js中全局配置:(如果是手动建的项目也要手动建一个nuxt.config.js

    // nuxt.config.js
    export default {
      modules: [
        '@nuxtjs/router'
      ]
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    原项目中的router/index.js拖进来放到顶级根目录下,并改名为router.js

    然后改写router.js

    • 懒加载全部改成直接引入
    • 抛出createRouter()函数
    import Vue from "vue";
    import VueRouter from "vue-router";
    
    // 安装插件 
    Vue.use(VueRouter);
    
    import Home from '@/pages/home.vue';
    import Project from '@/pages/project.vue';
    import Develop from '@/pages/develop/index.vue';
    
    import DevelopUs from '@/pages/develop/us.vue';
    
    // 配置路由映射
    const routes = [
      {
        name: 'home',
        path: '/home',
        component: Home,
      },
      {
        name: 'project',
        path: '/project',
        component: Project,
      },
      {
        name: 'develop',
        path: '/develop',
        component: Develop,
        children: [
          {
            path: 'us',
            component: DevelopUs,
          }
        ]
      }
    ]
    
    // 创建路由实例
    const router = new VueRouter({
      routes,
      mode: 'history'
    })
    
    export function createRouter() {
      return router;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    顺便建一下pages目录和.vue文件

    pages/
    --| home.vue
    --| project.vue
    --| develop/
    -----| index.vue
    -----| us.vue
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3. 配置路由重定向

    之前在vue-cli中配置的👇在nuxt中就不管用了

    {
       path: '',
       redirect: '/home'
     }
    
    • 1
    • 2
    • 3
    • 4

    正确配置:

    // nuxt.config.js
    router: {
      extendRoutes(routes) {
        routes.push({
          path: '/',
          redirect: '/home'
        })
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    4. 配置一些全局的css

    新建目录static,子目录css
    把所有全局的css都拖进来
    不需要webpack进行处理的css文件就放在static目录下,需要处理的就放在assets目录下

    全局配置:

    css: [
      '~/static/css/main.css'
    ]
    
    • 1
    • 2
    • 3

    (有一个字体文件引入的时候一直报错,后来把它名字里的空格删掉了就成功了,但是带空格的命名在原vue-cli项目中并未出错


    5. 使用sass

    我们在组件中的样式需要使用sass

    使用sass需要安装:
    npm i node-sass sass-loader -D
    👆这是官网给的,但是按这样安装我是报错了,根据错误提示我把sass-loader的版本改为了^10.1.1
    但是又会出现webpack版本冲突问题,先卸载掉原来的webpack
    npm uninstall webpack
    再安装它提示给的版本:
    npm i webpack@4.46.0 -D


    6. 编写公共头部布局模板

    在原项目中,是有一个公共的导航栏作为头部,这个导航栏是塞到了App.vue中,然后根据路由切换显示导航栏下的页面
    nuxt中可以把这个头部写成默认的布局模板

    新建目录layouts,新建文件default.vue
    然后cv过来,注意要添加来显示页面的主体内容

    <template>
      <div id="navigator">
    	<h1>h1>
    	<nuxt />
      div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    default.vue在其他页面中使用是不需要显式指定的

    如果有其他的布局模板比如叫blog.vue,在使用的页面中就需要配置layout属性:

    export default {
      layout: 'blog'
    }
    
    • 1
    • 2
    • 3

    7. 改写组件

    引入组件的import语句和components属性都可以删掉
    只要在nuxt.config.js配置一句components: true,组件就可以自动引入直接食用了


    8. 改写请求接口

    页面中涉及请求的部分就需要对请求接口进行改写
    (后台是有对跨域做处理的,这里就不配置代理了

    安装axios
    npm i @nuxtjs/axios -S

    nuxt.config.js中配置:

    modules: [
      '@nuxtjs/router',
      '@nuxtjs/axios'
    ],
    axios: {
      baseURL: '...',
      // http:// 改为 https://
      https: true,
    },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    接下来要改写axios的封装
    新建plugins目录,新建文件axios.js
    nuxt.config.js中配置:

    plugins: [
      '~/plugins/axios.js'
    ]
    
    • 1
    • 2
    • 3

    把原来的cv进来,注意拦截器写法要改变

    export default ({ $axios }) => {
      // 请求拦截
      $axios.onRequest(config => {})
      // 响应拦截
      $axios.onResponse(response => {})
      // 错误处理
      $axios.onError(err => {})
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    更多配置看官网:axios.nuxtjs.org

    并且原项目还有单独的api目录,里面有文件封装了请求接口的函数,这里也要改
    我们也新建一个api目录,拿一个文件user.js举例
    先在nuxt.config.js中配置一下:

    plugins: [
      '~/plugins/axios.js',
      '~/api/user.js'
    ]
    
    • 1
    • 2
    • 3
    • 4
    // api/user.js
    export default ({ $axios }, inject) => {
      // 第一个参数是原先的函数名
      inject('login', (username, password) => $axios({
        method: 'POST',
        url: '/login',
        data: {
          username,
          password,
        }
      }))
      inject('register', () => $axios({
        method: 'POST',
        url: '/register',
      }))
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在页面中的使用方法也要改:
    之前写在created()中的请求可以写在asyncData()

    export default{
      data() {
        return {
          username: '',
          password: ''
        }
      },
      async asyncData(app) {
        // $后跟着的就是上面的函数名
        const res = await app.$login(this.username, this.password)
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    methods中的使用:

    export default{
      data() {
        return {
          username: '',
          password: '',
          detail: {}
        }
      },
      methods: {
        async getUserInfo() {
          const data = await this.$login(this.username, this.password);
          this.detail = data;
    	}
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    9. 改写vuex

    新建目录store,新建文件index.js
    然后把原来的store/index.jscv过来

    再进行改写:

    const store = () => new Vuex.Store({
    })
    
    • 1
    • 2

    原项目比较简单没有分模块,所以这里改写也很简单啦


    10. 引入第三方插件

    使用了elementswipervant

    element:
    安装:npm i element-ui -S

    plugins目录下新建element.js

    // plugins/element.js
    import Vue from 'vue';
    import ElementUI from 'element-ui';
    
    Vue.use(ElementUI);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    全局配置:

    // nuxt.config.js
    plugins: [
      '~/plugins/element.js'
    ]
    
    • 1
    • 2
    • 3
    • 4

    swiper:
    👇是原项目的版本
    安装:npm i vue-awesome-swiper @3.1.3

    plugins目录下新建swiper.js
    必须这样写,不然在服务端没有window对象就会报错

    import Vue from 'vue'
    import 'swiper/dist/css/swiper.css'
    
    if (process.browser) {
      const VueAwesomeSwiper = require('vue-awesome-swiper/dist/ssr')
      Vue.use(VueAwesomeSwiper)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    全局配置:

    // nuxt.config.js
    plugins: [
      '~/plugins/swiper.js'
    ]
    
    • 1
    • 2
    • 3
    • 4

    使用的写法也要改
    参照文档:https://github.com/surmon-china/vue-awesome-swiper/tree/v3.1.3
    里面有提到spa ssr的写法是不同的

    <template>
      <div v-swiper:mySwiper="swiperOption" @someSwiperEvent="callback">
        <div class="swiper-wrapper">
          <div class="swiper-slide" v-for="item in list">
            
          div>
        div>
        
        <div class="swiper-pagination">div>
      div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    vant:
    安装原项目版本2.4.2
    npm i vant@2.4.2 -S
    (不指定版本号安装最新版本vant可能会报错,不匹配vue2版本)

    plugins目录下新建vant.js

    import Vue from "vue";
    import Vant from "vant";
    import 'vant/lib/index.css';
    Vue.use(Vant);
    
    • 1
    • 2
    • 3
    • 4

    全局配置:

    // nuxt.config.js
    plugins: [
      '~/plugins/vant.js'
    ]
    
    • 1
    • 2
    • 3
    • 4

    11. 配置meta

    原项目是利用插件vue-meta-info配置的meta,重要的两个属性keywordsdescription
    description是多个页面通用的,现在写在全局
    keywords每个页面不同,分开写在各个页面

    // nuxt.config.js
    export default {
      head: {
        meta: [
          {
            hid: "description",
    	    name: "description",
    		content: "xxx"
    	  },
    	  // 这里不能忘了加
    	  {
            hid: 'viewport',
            name: 'viewport',
            content: 'width=device-width, initial-scale=1.0, user-scalable=no'
          }
        ]
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    // home.vue
    export default {
      head() {
        return {
          meta: [
            hid: "keywords",
            name: "keywords",
            content: "xxx,xxx,xxxx,xxxx"
          ]
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    12. 开启gzip、brotli压缩

    安装插件nuxt-precompress:
    npm i nuxt-precompress

    nuxt.config.js中配置:

    modules: [ 'nuxt-precompress'],
    nuxtPrecompress: {
       enabled: true,
       report: false,
       test: /\.(js|css|html|txt|xml|svg)$/,
       // Serving options
       middleware: {
         enabled: true,
         enabledStatic: true,
         encodingsPriority: ['br', 'gzip']
       },
       gzip: {
         enabled: true,
         // 中间件将查找此文件名
         filename: '[path].gz[query]',
         threshold: 10240,
         minRatio: 0.8,
         // 压缩级别
         compressionOptions: { level: 9 }
       },
       brotli: {
         enabled: true,
         filename: '[path].br[query]',
         compressionOptions: { level: 11 },
         threshold: 10240,
         minRatio: 0.8
       }
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    运行npm run build
    .nuxt/dist/client中查看是否有.gz.br结尾的文件


    13. 部署

    执行npm run build
    会在.nuxt中生成一个dist文件夹

    .nuxtstaticpackage.jsonnuxt.config.js四个文件发给后端

    如何部署让后端看这篇文章叭。。😢
    https://blog.csdn.net/qq_40060547/article/details/124656244


    完😩

  • 相关阅读:
    Chrome扩展的核心:manifest 文件(上)
    【C++深入浅出】C/C++内存管理(教你如何new到对象)
    CCRC-DSO学员分享:数据安全官——导师与朋友的双重身份
    QT刷题系统
    操作系统文件使用磁盘的实现---20
    云计算-Linux-软链接与硬链接,获取命令帮助,系统运行级别,关机和重启
    Python3操作MongoDB数据库
    2022年湖北劳务资质如何办理?劳务资质不分等级
    Java8新特性你知道哪些?
    推荐几个制作svg的工具
  • 原文地址:https://blog.csdn.net/gegegegege12/article/details/126465183