フロントエンド プロジェクトを構築するための vue-cli4+vant+rem+sass+vuex+axios パッケージ化+webpack

モバイルプロジェクトテンプレート

vue-cli4.0 + webpack 4 + vant ui + sass + rem適応スキーム + axios パッケージに基づいて、携帯電話テンプレートのスキャフォールディングを構築
ここに画像の説明を挿入

スタートアッププロジェクト

git clone https://github.com/teach-tian/h5-vue-cli4.git

cd h5-vue-cli4

npm install

npm run serve

複数の環境変数を構成する

package.jsonscripts構成内でserve test build--mode xxx異なる環境を実行するために

npm run serveローカルで起動、パッケージテストdevelopment
で実行、パッケージ公式で実行、実行npm run testtesting
npm run buildproduction

"scripts": {
  "serve": "vue-cli-service serve --open",
  "test": "vue-cli-service build --mode testing",
  "build": "vue-cli-service build",
}

構成の紹介

以 VUE_APP_先頭の変数には、コード内の process.env.VUE_APP_ を通じてアクセスできます。
たとえば、VUE_APP_ENV = 'development'process.env.VUE_APP_ENV を通じてアクセスします。
変数に加えてVUE_APP_*、アプリケーション コードで常に使用できる 2 つの特別な変数がありますNODE_ENVBASE_URL

プロジェクトのルート ディレクトリに新しい .env.* を作成します。

.env.development 本地开发环境配置
NODE_ENV='development'

.env.staging 测试环境配置
NODE_ENV='production'

.env.production 正式环境配置
 NODE_ENV='production'
这里我们并没有定义很多变量,只定义了基础的 VUE_APP_ENV development testing production
变量我们统一在 src/config/env.*.js 里进行管理。

ここで質問ですが、環境に応じて変数を設定するためのファイルがあるのに、なぜ config の下に対応するファイルを 3 つ作成する必要があるのでしょうか?

修改起来方便,不需要重启项目,符合开发习惯。
config/index.js

// 根据环境引入不同配置 process.env.NODE_ENV
const config = require('./env.' + process.env.NODE_ENV)
module.exports = config

環境に対応する変数を構成します。例としてローカル環境ファイル env.development.js を取り上げます。ユーザーはニーズに応じて変更できます。

// 本地环境配置
module.exports = {
  title: 'vue-h5-template',
  baseUrl: 'http://localhost:9018', // 项目地址
  baseApi: 'https://test.xxx.com/api', // 本地api请求地址
  APPID: 'xxx',
  APPSECRET: 'xxx'
}

環境によって変数は異なります

// 異なる環境に応じて異なる BaseApi アドレスを導入します

import { baseApi } from '@/config'
console.log(baseApi)

レム適応ソリューション

心配しないでください。プロジェクトは rem 適応で構成されています。以下は単なる紹介です。

Vant のスタイルでは、デフォルトで px が単位として使用されます。rem 単位を使用する必要がある場合は、次の 2 つのツールをお勧めします。

postcss-pxtorem は単位を rem に変換するために使用される postcss プラグインです
lib-flexible は rem ベンチマーク値を設定するために使用されます
プラグインのインストールとインポート

1. 依存関係をインストールする

cnpm install lib-flexible [email protected] --save-dev
  1. main.jsインポート
// 移动端适配
 import 'lib-flexible/flexible'; 
PostCSS 配置
1.创建.postcssrc.js

以下に基本的な postcss 構成を示します。この構成に基づいてプロジェクトの要件に応じて変更できます。

// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
  plugins: {
    autoprefixer: {
      overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 31', 'ff > 31', 'ie >= 8']
    },
    'postcss-pxtorem': {
      rootValue: 37.5,
      propList: ['*']
    }
  }
}

初心者必見、老鳥はスキップ

多くの友人が適応の問題について私に尋ねます。Vant UI を使用しているため、Vant UI 375 の設計仕様に従う必要があります。通常、私たちの設計
では UI マップを Blue Lake にアップロードし、必要に応じてそれを使用できます 次はレムを普及させましょう。

1rem が html ルート要素によって設定された font-size の px 値に等しいことがわかっています。Vant UI は rootValue: 37.5 を設定します。これは iPhone 6 で確認できます
(1rem は 37.5px に相当します)。

<html data-dpr="1" style="font-size: 37.5px;"></html>

異なるモデル間で切り替えると、ルート要素のフォント サイズが異なる場合があります。css px スタイルを記述すると、プログラムによって rem に変換され、適応が実現されます。

Vant コンポーネントを使用するため、rootValue: 37.5 に従ってスタイルを記述する必要があります。

例: iPhone6 では 750px * 1334px の画像が画面いっぱいに表示されるデザインですが、他のモデルにも適用されます。

rootValue: 75、style width: 750px; height: 1334px; の場合、写真は iPhone6 の画面いっぱいに表示され、この時点で他のモデルに切り替えると、写真もいっぱいになります

rootValue: 37.5の場合、スタイル幅: 375px; 高さ: 667px; 写真がiPhone6の画面いっぱいに表示されます。
つまり、iPhone 6では幅375pxのCSSを記述します。その他の場合は、設計図面に従って対応するスタイルを記述することができます。

もちろん、画面全体に表示したい場合は 100% を使用できます。これは単なる例です。

<img class="image" src="https://www.sunniejs.cn/static/weapp/logo.png" />

<style>
  /* rootValue: 75 */
  .image {
    width: 750px;
    height: 1334px;
  }
  /* rootValue: 37.5 */
  .image {
    width: 375px;
    height: 667px;
  }
</style>

Sass グローバル スタイル

まず、node-sassインストールが失敗する場合がありますが、諦めずに何度か試してください。

各ページの対応するスタイルは、独自の .vue ファイルに書き込まれます。scoped` は、名前が示すように、CSS にドメインの概念を追加します。

<style lang="scss">
  /* global styles */
</style>

<style lang="scss" scoped>
  /* local styles */
</style>

ディレクトリ構造
vue-h5-template すべてのグローバル スタイルは @/src/assets/css ディレクトリの下に設定されます

§── アセット
│ §── css
│ │ §──index.scss # グローバル汎用スタイル
│ │ §── mixin.scss # グローバルミックスイン
│ │ └── variables.scss # グローバル変数

カスタム vant-ui スタイル
次に、vant-ui スタイルをオーバーライドする方法について説明します。vant-ui のスタイルはグローバルに導入されるため、特定のページでそのスタイルをオーバーライドしたい場合は、scoped を追加できませんが、
このページの vant スタイルのみをオーバーライドしたい場合は、その親に追加できます。クラスを作成し、名前空間を使用して問題を解決します。

.about-container {
  /* 你的命名空间 */
  .van-button {
    /* vant-ui 元素*/
    margin-right: 0px;
  }
}

親コンポーネントが子コンポーネントのスタイルを変更する 深度セレクター
子コンポーネントがスコープ付きを使用しているが、親コンポーネント内の子コンポーネントのスタイルを変更したい場合は、>>> を使用して次のことを実現できます。

グローバル変数
vue.config.js 設定は css.loaderOptions オプションを使用して Sass mixin 変数をグローバルに挿入します。手動でインポートする必要はありません。変数の形式で cdn アドレスをインポートするように $cdn
を設定します。これにより、すべての Sass/Lessスタイルは共有グローバル変数に渡されます。

const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV)
const defaultSettings = require('./src/config/index.js')
module.exports = { css: { extract: IS_PROD, sourceMap: false, loaderOptions: { // scss-loader にオプションを渡しますscss: { //グローバルに挿入され、$cdn はイメージ cdn を構成できます// 詳細: https://cli.vuejs.org/guide/css.html #プリプロセッサローダーにオプションを渡すprependData: } } } }






sassmixin variables

@import "assets/css/mixin.scss"; @import "assets/css/variables.scss"; $cdn: "${defaultSettings.$cdn}";




设置 js 中可以访问 $cdn,.vue 文件中使用this.$cdn访问

// グローバル スタイル
のインポート '@/assets/css/index.scss'を導入します

// $cdn を js でアクセスできるように設定します
// cdn を導入します
import { KaTeX 解析エラー: 'EOF' が予期され、位置 5 で '}' を取得しました: cdn }̲ from '@/config... cdn = $cdn



CSSとJSで使用する

Vuex 状態管理

ディレクトリ構造

§── ストア
│ ├── モジュール
│ │ └── app.js
│ §── Index.js
│ ├── getters.js

main.js 引入

import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

使用

<script>
  import { mapGetters } from 'vuex'
  export default {
    computed: {
      ...mapGetters(['userName'])
    },

    methods: {
      // Action 通过 store.dispatch 方法触发
      doDispatch() {
        this.$store.dispatch('setUserName', '真乖,赶紧关注公众号,组织都在等你~')
      }
    }
  }
</script>

Vueルーター

このケースではハッシュ モードが採用されており、開発者は要件に応じてモード ベースを変更します。

注: 履歴モードを使用する場合は、それに応じて vue.config.js の publicPath を変更する必要があります。

:vue.config.js基本設定に移動

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)
export const router = [
  {
    path: '/',
    name: 'index',
    component: () => import('@/views/home/index'), // 路由懒加载
    meta: {
      title: '首页', // 页面标题
      keepAlive: false // keep-alive 标识
    }
  }
]
const createRouter = () =>
  new Router({
    // mode: 'history', // 如果你是 history模式 需要配置 vue.config.js publicPath
    // base: '/app/',
    scrollBehavior: () => ({ y: 0 }),
    routes: router
  })

export default createRouter()

js で cdn にアクセスしたり、.vue ファイルでこれを使用したり、.cdn および .vue ファイルでこれを使用したりできます。c d n .vueファイルこの.cdnアクセスを使用ます

// 引入全局样式
import '@/assets/css/index.scss'

// 设置 js中可以访问 $cdn
// 引入cdn
import { $cdn } from '@/config'
Vue.prototype.$cdn = $cdn

在 css 和 js 使用

<script>
  console.log(this.$cdn)
</script>
<style lang="scss" scoped>
  .logo {
    width: 120px;
    height: 120px;
    background: url($cdn + '/weapp/logo.png') center / contain no-repeat;
  }
</style>

Webpack 4 vue.config.js の基本設定
Vue Router モードが hash の場合

publicPath: './',

如果你的 Vue Router 模式是 history 这里的 publicPath 和你的 Vue Router base 保持一直

publicPath: '/app/',
1
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV)

module.exports = {
  publicPath: './', // 署应用包时的基本 URL。 vue-router hash 模式使用
  //  publicPath: '/app/', // 署应用包时的基本 URL。  vue-router history模式使用
  outputDir: 'dist', //  生产环境构建文件的目录
  assetsDir: 'static', //  outputDir的静态资源(js、css、img、fonts)目录
  lintOnSave: !IS_PROD,
  productionSourceMap: false, // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
  devServer: {
    port: 9020, // 端口号
    open: false, // 启动后打开浏览器
    overlay: {
      //  当出现编译器错误或警告时,在浏览器中显示全屏覆盖层
      warnings: false,
      errors: true
    }
    // ...
  }
}

エイリアスの構成 alias

const path = require('path')
const resolve = dir => path.join(__dirname, dir)
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV)

module.exports = {
  chainWebpack: config => {
    // 添加别名
    config.resolve.alias
      .set('@', resolve('src'))
      .set('assets', resolve('src/assets'))
      .set('api', resolve('src/api'))
      .set('views', resolve('src/views'))
      .set('components', resolve('src/components'))
  }
}

Eslint + Pettier の統一開発仕様

VScode (バージョン 1.47.3) は、eslint prettier vetur プラグインをインストールします。Vue ファイルは vetur を使用してフォーマットされ、その他のファイルは prettier を使用します。後で、
これら 3 つを一緒に使用する方法を具体的に書きます

細かいルールを .prettierrc ファイルに記述します。

{
   "printWidth": 120,
   "tabWidth": 2,
   "singleQuote": true,
   "trailingComma": "none",
   "semi": false,
   "wrap_line_length": 120,
   "wrap_attributes": "auto",
   "proseWrap": "always",
   "arrowParens": "avoid",
   "bracketSpacing": false,
   "jsxBracketSameLine": true,
   "useTabs": false,
   "overrides": [{
       "files": ".prettierrc",
       "options": {
           "parser": "json"
       }
   }]
}

vscode設定.json設定

    {
  // 将设置放入此文件中以覆盖默认设置
  "files.autoSave": "off",
  // 控制字体系列。
  "editor.fontFamily": "Consolas, 'Courier New', monospace,'宋体'",
  "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",
  // 以像素为单位控制字号。
  "editor.fontSize": 16,
  // 控制选取范围是否有圆角
  "editor.roundedSelection": false,
  // 建议小组件的字号
  "editor.suggestFontSize": 16,
  // 在“打开的编辑器”窗格中显示的编辑器数量。将其设置为 0 可隐藏窗格。
  "explorer.openEditors.visible": 0,
  // 是否已启用自动刷新
  "git.autorefresh": true,
  // 以像素为单位控制终端的字号,这是 editor.fontSize 的默认值。
  "terminal.integrated.fontSize": 14,
  // 控制终端游标是否闪烁。
  "terminal.integrated.cursorBlinking": true,
  // 一个制表符等于的空格数。该设置在 `editor.detectIndentation` 启用时根据文件内容进行重写。
  // Tab Size
  "editor.tabSize": 2,
  // By default, common template. Do not modify it!!!!!
  "editor.formatOnType": true,
  "window.zoomLevel": 0,
  "editor.detectIndentation": false,
  "css.fileExtensions": ["css", "scss"],
  "files.associations": {
    "*.string": "html",
    "*.vue": "vue",
    "*.wxss": "css",
    "*.wxml": "wxml",
    "*.wxs": "javascript",
    "*.cjson": "jsonc",
    "*.js": "javascript"
  },
  // 为指定的语法定义配置文件或使用带有特定规则的配置文件。
  "emmet.syntaxProfiles": {
    "vue-html": "html",
    "vue": "html"
  },
  "search.exclude": {
    "**/node_modules": true,
    "**/bower_components": true
  },
  //保存时eslint自动修复错误
  "editor.formatOnSave": true,
  // Enable per-language
  //配置 ESLint 检查的文件类型
  "editor.quickSuggestions": {
    "strings": true
  },
  // 添加 vue 支持
  // 这里是针对vue文件的格式化设置,vue的规则在这里生效
  "vetur.format.options.tabSize": 2,
  "vetur.format.options.useTabs": false,
  "vetur.format.defaultFormatter.html": "js-beautify-html",
  "vetur.format.defaultFormatter.css": "prettier",
  "vetur.format.defaultFormatter.scss": "prettier",
  "vetur.format.defaultFormatter.postcss": "prettier",
  "vetur.format.defaultFormatter.less": "prettier",
  "vetur.format.defaultFormatter.js": "vscode-typescript",
  "vetur.format.defaultFormatter.sass": "sass-formatter",
  "vetur.format.defaultFormatter.ts": "prettier",
  "vetur.format.defaultFormatterOptions": {
    "js-beautify-html": {
      "wrap_attributes": "aligned-multiple", // 超过150折行
      "wrap-line-length": 150
    },
    // #vue组件中html代码格式化样式
    "prettier": {
      "printWidth": 120,
      "tabWidth": 2,
      "singleQuote": false,
      "trailingComma": "none",
      "semi": false,
      "wrap_line_length": 120,
      "wrap_attributes": "aligned-multiple", // 超过150折行
      "proseWrap": "always",
      "arrowParens": "avoid",
      "bracketSpacing": true,
      "jsxBracketSameLine": true,
      "useTabs": false,
      "overrides": [
        {
          "files": ".prettierrc",
          "options": {
            "parser": "json"
          }
        }
      ]
    }
  },
  // Enable per-language
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "vetur.validation.template": false,
  "html.format.enable": false,
  "json.format.enable": false,
  "javascript.format.enable": false,
  "typescript.format.enable": false,
  "javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": false,
  "[html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[jsonc]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[vue]": {
    "editor.defaultFormatter": "octref.vetur"
  },
  "emmet.includeLanguages": {
    "wxml": "html"
  },
  "[typescriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  // 开启eslint自动修复js/ts功能
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "minapp-vscode.disableAutoConfig": true,
  "javascript.implicitProjectConfig.experimentalDecorators": true,
  "editor.maxTokenizationLineLength": 200000
}

おすすめ

転載: blog.csdn.net/weixin_52703987/article/details/130885847