Nuxt.js + vant-ui 实现移动端按需加载开发,换算比例自定义,oss配置

1,367 阅读2分钟

注意脚手架安装的方式不是按需加载的。是全量加载

根据nuxt 脚手架安装

目录结构如下:

image-20210720103633599

Nuxt.config.js 配置

const fs = require('fs')
const path = require('path')
const responsiveJS = fs.readFileSync(
  path.resolve(__dirname, './plugins/lib-flexible.js'), //  导入淘宝rem,也可以使用vw单位做适配,这一步就可以省略,配置相应的vw插件 postcss-px-to-viewport
  'utf8'
)
export default {
  // Target: https://go.nuxtjs.dev/config-target
  target: 'static',
  server: {
    port: 3000,
    host: '0.0.0.0', // default: localhost,
  },
  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    title: 'nuxt-vant-mobile',
    htmlAttrs: {
      lang: 'zh-CN', // zh-Hans-CN 标准最新版本,兼容目前还是写zh-CN
    },
    meta: [
      {
        charset: 'utf-8',
      },
      {
        name: 'viewport',
        content:
          'width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover',
      },
      {
        hid: 'description',
        name: 'description',
        content: '',
      },
    ],
    link: [
      {
        rel: 'icon',
        type: 'image/x-icon',
        href: '/favicon.ico',
      },
    ],
    script: [
      {
        innerHTML: responsiveJS,
        type: 'text/javascript',
      },
    ],
    __dangerouslyDisableSanitizers: ['script'], // 直接把js内容 写入到页面
  },
​
  // Global CSS: https://go.nuxtjs.dev/config-css
  css: ['@/assets/style/index.less'],
​
  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
    {
      src: '@/plugins/vue-vant',
    },
  ],
​
  // Auto import components: https://go.nuxtjs.dev/config-components
  components: true,
​
  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
    // https://go.nuxtjs.dev/eslint
    '@nuxtjs/eslint-module',
  ],
​
  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    // https://go.nuxtjs.dev/axios
    '@nuxtjs/axios',
    '@nuxtjs/style-resources',
  ],
  styleResources: {
    less: ['./assets/style/variable.less'],
  },
  // Axios module configuration: https://go.nuxtjs.dev/config-axios
  axios: {},
​
  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
    // publicPath: process.env.ASSETS_TO_OSS === 'true' ?
    // 'oss地址' : null,
    extend(config, { isDev, isClient }) {
      // Run ESLint on save
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/,
          options: {
            fix: true,
          },
        })
      }
    },
    extractCSS: true, // 提取css到单独link文件
    transpile: [/^vant/],
    postcss: {
      plugins: {
        autoprefixer: {},
        // postcss-pxtorem 插件的版本需要 >= 5.0.0
        'postcss-pxtorem': {
          rootValue({ file }) {
            return file.includes('/vant/lib/') ? 37.5 : 75 // 针对vant 文件设置37.5,其他页面 因为页面设计稿为750设计的 设置75
          },
          propList: ['*'],
          unitPrecision: 5,
          minPixelValue: 2,
          // replace: false, // 是否显示px 回退
        },
      },
    },
    babel: {
      plugins: [
        [
          'import',
          {
            libraryName: 'vant',
            style: (name) => {
              return `${name}/style/less.js`
            },
          },
          'vant',
        ],
      ],
    },
    optimization: {
      splitChunks: {
        // 代码打包分割规则
        cacheGroups: {
          vant: {
            name: 'chunk-vant',
            priority: 10,
            test: /[\/]node_modules[\/]_?vant(.*)/,
          },
        },
      },
    },
    loaders: {
      less: {
        javascriptEnabled: true,
        modifyVars: {
          // 直接覆盖变量
          // 'font-size-md': '40px',
          hack: `true; @import "${path.join(
            __dirname,
            './assets/style/vant-var.less'
          )}";`,
        },
      },
    },
  },
}
​

plugins 目录引入使用的vant 组件

import Vue from 'vue'
import {
  Button,
  Dialog,
  Toast,
  Icon,
  Overlay,
  Sticky,
  Grid,
  GridItem,
  Image as VanImage,
  Lazyload,
  Tab,
  Tabs,
} from 'vant'// 引入 Dialog 组件后,会自动在 Vue 的 prototype 上挂载 $dialog 方法,在所有组件内部都可以直接调用此方法。
Vue.use(Button)
Vue.use(Dialog)
Vue.use(Toast)
Vue.use(Icon)
Vue.use(Overlay)
Vue.use(Sticky)
Vue.use(Grid)
Vue.use(GridItem)
Vue.use(VanImage)
Vue.use(Lazyload, {
  preLoad: 1.3,
  attempt: 1,
})
Vue.use(Tab)
Vue.use(Tabs)
​

配置阿里OSS,将打包后的dist文件夹上传到阿里oss,开启cdn

项目根目录创建 oss.config.js

module.exports = {
  region: 'oss-cn-shenzhen',  
  bucket: '', 
  accessKeyId: '', 
  accessKeySecret: '' 
};
​

package.json文件配置上传命令 generate-oss-upload 使用npm run generate-oss-upload

"scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "build:stage": "nuxt build --mode staging",
    "analyze": "nuxt build --analyze",
    "start": "nuxt start",
    "generate": "nuxt generate && npm run echo",
    "generate-oss-upload": "nuxt generate && npm run oss && npm run echo",
    "oss": "cross-env ASSETS_TO_OSS=true oss-upload dist -o /oss",
    "lint:js": "eslint --ext ".js,.vue" --ignore-path .gitignore .",
    "lint": "npm run lint:js"
  },

nuxt.config.js 配置 oss 上传地址

build: {
     publicPath: process.env.ASSETS_TO_OSS === 'true' ? 'oss地址' : null,
}