cli 开发 uni-app

MuYan2022-10-24VueVueuni-app

环境安装

  • 全局安装 vue-cli

TIP

目前仍推荐使用 vue-cli 4.x,对于 vue-cli 5.x / Webpack 5 的支持情况参考 #3723open in new window

npm install -g @vue/cli@4.5.15

创建 uni-app

  • 使用正式版(对应HBuilderX最新正式版)
vue create -p dcloudio/uni-preset-vue my-project

# 选择:默认模板(TypeScript) 
# Preset options:
# ? 请选择 uni-app 模板  
#   默认模板
# > 默认模板(TypeScript) 
#   Hello uni-app        
#   前后一体登录模板     
#   看图模板
#   新闻/资讯类模板      
#   自定义模板
  • 使用Vue3/Vite版 (目前只能用于尝鲜,生态还不太完整)
npx degit dcloudio/uni-preset-vue#vite-ts my-vue3-project

配置 eslint、parser

  • 安装依赖
npm i @vue/cli-plugin-eslint @vue/eslint-config-typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-plugin-vue eslint prettier -D
  • eslint: ESLint 的核心代码

  • prettier: prettier 插件的核心代码

  • eslint-plugin-vue: 包含常用的 vue 规范

  • @typescript-eslint/parser: ESLint 的解析器,用于解析 typescript,从而检查和规范 Typescript 代码

  • @typescript-eslint/eslint-plugin: 包含了各类定义好的检测 Typescript 代码的规范

  • @vue/eslint-config-typescript: 用于vue-cli的eslint-config-typescript

  • @vue/cli-plugin-eslint: Eslint 的插件 vue-cli

  • 如果安装后存在问题可以考虑使用以下版本

"eslint": "^8.25.0",
"prettier": "^2.7.1",
"eslint-plugin-vue": "^9.6.0",
"@typescript-eslint/parser": "^5.40.0",
"@typescript-eslint/eslint-plugin": "^5.40.0",
"@vue/eslint-config-typescript": "^11.0.2",
"@vue/cli-plugin-eslint": "^5.0.8",

创建 eslint 相关文件

  • 创建 .eslintrc.js 配置文件
// .eslintrc.js
module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: [
    'plugin:vue/essential',
    'eslint:recommended',
    '@vue/typescript/recommended',
  ],
  parserOptions: {
    ecmaVersion: 2020,
  },
  globals: {
    ROUTES: true,
    uni: true,
  },
  rules: {
    // 禁止对象字面量中出现重复的 key
    'no-empty': 1,
    // 禁止出现重复的 case 标签
    'no-duplicate-case': 2,
    // 禁止对象字面量中出现重复的 key
    'no-dupe-keys': 2,
    // 禁止 function 定义中出现重名参数
    'no-dupe-args': 2,
    // 指定程序中允许的最大环路复杂度
    complexity: ['error', 5],
    // 要求 return 语句要么总是指定返回的值,要么不指定
    'consistent-return': 1,
    // 强制所有控制语句使用一致的括号风格
    curly: 2,
    // 要求使用 === 和 !==
    eqeqeq: 2,
    // 强制每个文件中包含的的类的最大数量
    'max-classes-per-file': ['error', 1],
    // 不允许在 case 子句中使用词法声明
    'no-case-declarations': 2,
    // 禁止 if 语句中 return 语句之后有 else 块
    'no-else-return': 2,
    // 禁止使用空解构模式
    'no-empty-pattern': 2,
    // 禁用 eval()
    'no-eval': 2,
    // 禁止扩展原生类型
    'no-extend-native': 2,
    // 禁止 case 语句落空
    'no-fallthrough': 2,
    // 禁止数字字面量中使用前导和末尾小数点
    'no-floating-decimal': 2,
    'no-global-assign': 2,
    // 禁止 this 关键字出现在类和类对象之外
    'no-invalid-this': 2,
    // 禁用不必要的嵌套块
    'no-lone-blocks': 2,
    // 禁止出现多个空格
    'no-multi-spaces': 2,
    // 禁止多行字符串
    'no-multi-str': 2,
    // 禁止重新声明变量
    'no-redeclare': 2,
    // 禁止在 return 语句中使用赋值语句
    'no-return-assign': 2,
    // 禁用不必要的 return await
    'no-return-await': 2,
    // 禁止自我赋值
    'no-self-assign': 2,
    // 禁止使用不带 await 表达式的 async 函数
    'require-await': 2,
    // 要求或禁止 var 声明中的初始化
    'init-declarations': 2,
    // 禁止将标识符定义为受限的名字
    'no-shadow-restricted-names': 2,
    // 要求或禁止类成员之间出现空行
    'lines-between-class-members': 1,
    // 要求使用骆驼拼写法
    camelcase: 2,
    // 要求或禁止在注释前有空白
    'spaced-comment': ['error', 'always'],
    // 强制函数中的变量在一起声明或分开声明
    'one-var': ['error', 'never'],
    'line-comment-position': ['error', { position: 'above' }],
    // 强制函数最大代码行数
    'max-lines-per-function': ['error', 30],
    'lines-around-comment': [
      'error',
      {
        beforeBlockComment: true,
        allowClassStart: true,
        allowObjectStart: true,
      },
    ],
    // 禁止变量声明与外层作用域的变量同名
    '@typescript-eslint/no-shadow': 2,
    // 禁止出现未使用过的变量
    '@typescript-eslint/no-unused-vars': 2,
    '@typescript-eslint/explicit-module-boundary-types': 0,
    '@typescript-eslint/no-explicit-any': 0,
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
  },
};
  • 创建 .eslintignore 免校验文件
// .eslintignore
babel.config.js
postcss.config.js
vue.config.js
  • 创建 .prettierrc 文件
{
  "printWidth": 80,
  "semi": true,
  "trailingComma": "all",
  "bracketSpacing": true,
  "requirePragma": false,
  "proseWrap": "preserve",
  "singleQuote": true
}
  • vscode 配置保存后自动格式化

【ctrl +shift +p】——【settings.json(首选项:打开设置(json))】,打开IDE 的 settings.json 文件后,进行以下配置

注:vs code 版本 1.52.1 (user setup),老版本配置可能存在不一致(自行百度)

// settings.json
// 保存时eslint自动修复错误
"editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
},
"editor.formatOnSave": true

配置 tailwindcss

1. 安装依赖

  • 基础依赖
npm i  weapp-tailwindcss-webpack-plugin tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9 -D
  • scss 依赖
npm i sass sass-loader@^10  -D

2. 配置 tailwind.config.js

// tailwind.config.js
module.exports = {  
  mode: 'jit',  
  purge: {  
    content: ['./src/**/*.{vue,js,ts,jsx,tsx,wxml}']  
  },  
  corePlugins: {  
    preflight: false  
  }  
}

3. 配置 postcss.config.js

const path = require('path');
module.exports = {
  parser: require('postcss-comment'),
  plugins: [
    require('postcss-import')({
      resolve(id, basedir, importOptions) {
        if (id.startsWith('~@/')) {
          return path.resolve(process.env.UNI_INPUT_DIR, id.substr(3));
        } else if (id.startsWith('@/')) {
          return path.resolve(process.env.UNI_INPUT_DIR, id.substr(2));
        } else if (id.startsWith('/') && !id.startsWith('//')) {
          return path.resolve(process.env.UNI_INPUT_DIR, id.substr(1));
        }
        return id;
      },
    }),
    require('autoprefixer')({
      remove: process.env.UNI_PLATFORM !== 'h5',
    }),
    // tailwindcss 相关配置
    require('tailwindcss')({
      config: path.resolve(__dirname, './tailwind.config.js'),
    }),
    require('@dcloudio/vue-cli-plugin-uni/packages/postcss'),
  ],
};

4. 设置环境变量

-添加 .env.development 文件设置 TAILWIND_MODE,这里只在开发环境配置就可以了,正式环境不要配置,不然会存在打包问题

注:这是为了兼容 tailwindcss v2 的 HMR 方案,如果你是用的是 tailwindcss v3 就不需要了

#  .env.development
# jit 模式 HMR  
TAILWIND_MODE=watch

5. 在 src/App.vue 中引用

<style lang="scss">  
/*每个页面公共css */
// 小程序需要 'base' 来注入变量,但不需要 html preflight
@import 'tailwindcss/base';  
@import 'tailwindcss/utilities';  
</style>

6. 在根目录下添加 vue.config.js

// vue.config.js  
const { UniAppWeappTailwindcssWebpackPluginV4 } = require('weapp-tailwindcss-webpack-plugin')  

/**  
 * @type {import('@vue/cli-service').ProjectOptions}  
 */  
const config = {  
  //....  
  configureWebpack: {  
    plugins: [new UniAppWeappTailwindcssWebpackPluginV4()]  
  }  
  //....  
}  

module.exports = config

使用基础示例

<view :class="[flag?'bg-red-900':'bg-[#fafa00]']">bg-[#fafa00]</view>  
<view :class="{'bg-[#098765]':flag===true}">bg-[#098765]</view>  
<view class="p-[20px] -mt-2 mb-[-20px] ">p-[20px] -mt-2 mb-[-20px] margin的jit 不能这么写 -m-[20px]</view>  
<view class="space-y-[1.6rem]">  
  <view class="w-[300rpx] text-black text-opacity-[0.19]">w-[300rpx] text-black text-opacity-[0.19]</view>  
  <view class="min-w-[300rpx] max-h-[100px] text-[20px] leading-[0.9]">min-w-[300rpx] max-h-[100px] text-[20px] leading-[0.9]</view>  
  <view class="max-w-[300rpx] min-h-[100px] text-[#dddddd]">max-w-[300rpx] min-h-[100px] text-[#dddddd]</view>  
  <view class="flex items-center justify-center h-[100px] w-[100px] rounded-[40px] bg-[#123456] bg-opacity-[0.54] text-[#ffffff]">Hello</view>  
  <view class="border-[10px] border-[#098765] border-solid border-opacity-[0.44]">border-[10px] border-[#098765] border-solid border-opacity-[0.44]</view>  
  <view class="grid grid-cols-3 divide-x-[10px] divide-[#010101] divide-solid">  
    <view>1</view>  
    <view>2</view>  
    <view>3</view>  
  </view>  
</view>
  • or @apply
<template>
  <view class="hello">world</view>
</template>  
<style lang="scss">  
.hello {  
  @apply flex items-center justify-center h-[100px] w-[100px] rounded-[40px] bg-[#123456] bg-opacity-[0.54] text-[#ffffff] #{!important};  
}  
</style>

正式环境删除 console

  • 安装依赖
npm i babel-plugin-transform-remove-console -D
  • 配置 babel.config.js
// babel.config.js
const plugins = []

// 正式环境删除 console
if (['production'].includes(process.env.NODE_ENV)) {
  plugins.push('transform-remove-console');
}

module.exports = {
  plugins
}

压缩代码

cli创建的项目可以在package.json中添加参数--minimize,示例:"dev:mp-weixin": "cross-env NODE_ENV=development UNI_PLATFORM=mp-weixin vue-cli-service uni-build --watch --minimize"

上次更新 2026/6/23 11:49:15
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.8