preface

Using VUE to build projects, clear project structure will improve the development efficiency, familiar with the various configurations of the project will also make the development efficiency higher, this is not long, purely share, hope to help Xiaobai improve the development efficiency, also welcome the discussion and correction of god

  • Github address: github.com/santa945/my…

The directory structure

Production │ eslintrc.js │ gitignore │ babel.config.js │ package-lock.json │ ├─ ├─public │ favicon. Ico │ index.html │ ├─ ├─ download.json │ ├.html │ ├─public │ favicon ├ ─ apis / / interface file according to the page or instance modular │ index. The js │ login. Js │ ├ ─ components/tools/component │ └ ─ the header │ index. The less │ index. The vue │ ├ ─ config │ env.js │ Index. Js │ ├─contant │ index. Js │ ├─images │ logo.png │ ├─pages │ env.js │ Index. Different instances of │ ├ ─ index / / primary instance │ │ │ index. The js │ │ │ index. The vue │ │ │ main. Js │ │ │ router. Js │ │ │ store. Js │ │ │ │ │ ├ ─ components │ ├─ ├─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0├ ─ sci-0└ Index.js │ index.vue │ ├─scripts Tool function │ │ map. Js │ │ │ └ ─ utils │ helper. Js │ ├ ─ store / / vuex warehouse │ │ index. The js │ │ │ ├ ─ index │ │ actions. Js │ │ getters. Js │ │ index. Js │ │ mutation - types. Js │ │ mutations. Js │ │ state. The js │ │ │ └ ─ user │ actions. Js │ getters. Js │ index. The js │ ├─ style, ├─ ├─ download.js │ mutations. Js │ state.js │ ├─animation │ index Slide. Less │ ├ ─ base │ index. The less │ style.css. Less │ var. Less │ widget. The less │ └ ─ common index. The less reset. Less style.css. Less transition.lessCopy the code

Vue. Confing. Js configuration

Use nodeJS to configure multiple entries for multiple pages. The code is more elegant. Here is a copy of the common vue.config.js configuration, with annotations

const path = require("path")
const fs = require("fs"/** * @readdirsync fs module, which is used to read all files/folders under the folder, returns an array, fs.readdir * @resolve path module, which is used to concatenate file paths * @existssync FS module, which is used to check whether the path exists. Returns a Boolean */ constdirs = fs.readdirSync(path.resolve(process.cwd(), "src/pages"))
const pages = dirs.reduce((config,dirname)=>{
    const filePath = `src/pages/${dirname}/main.js`
    const tplPath = path.resolve(process.cwd(), `./public/${dirname}.html`)

    if(fs.existsSync(tplPath)){
        config[dirname] = filePath
    }else{config[dirname] = {entry:filePath,// Page entry template:'public/index.html'// The source of the template filename: '${dirname}.html '// output in dist/xx.html}}return},{}) public/[dir-name].html; public/index.html /** * publicPath By default, applications will be deployed in the root path. Use publicPath to define deployment in subpaths. In Pages mode, do not use relative path * productionSourceMaptrueThe package generates a.map file * contentBase: tells the server to extract static files from that directory * COMPRESS: All services are gzip compressed *historyApiFallback: When using the HTML5 History API, any 404 response may need to be replaced with index.html *disableHostCheck: bypass the host check * devServer. Proxy. ChangeOrigin: by default, the agent will keep the source of the host header, you can set the changeOrigin totrue* devserver.proxy. secure: By default, backend servers running over HTTPS and using invalid certificates are not accepted, set tofalseExpress acceptance of * chainWebpack: Webpack chain operation * configureWebpack: may be an object, also may be a function, mainly through webpack - merge merged into the configuration * configureWebpack. Resolve: Equivalent to merge content to webpack original resolve [HTTP: / / https://webpack.docschina.org/configuration/resolve/#resolve]* configureWebpack. Resolve. Alias: create an import or require an alias, to ensure that the module is introduced into simpler * / module in exports = {publicPath: process.env.VUE_APP_MODE ==="production" ? "/prod/" : "/",
    pages,
    outputDir:process.env.VUE_APP_MODE === "production"? path.resolve(`${process.cwd()}/dist-prod/`):path.resolve(`${process.cwd()}/dist-beta/`),
    productionSourceMap:process.env.VUE_APP_MODE === "beta",
    devServer:{
        port:3434,
        host: "127.0.0.1",
        contentBase: "./dist",
        compress:true.historyApiFallback:true.disableHostCheck: true,
        proxy:{
            "/": {
                target: "http://10.122.122.10:8070",
                changeOrigin: true,
                secure: false,
                // pathRewrite: {"^/sjjc" : ""}
              },
        }

    },
    chainWebpack: config => {
        config.module
          .rule("images")
          .use("url-loader")
          .tap(args => {
            return {
              limit: 4096,
              fallback: {
                loader: "file-loader",
                options: {
                  name: "images/[name].[hash:8].[ext]",}}}; }); config.module .rule("svg")
          .use("file-loader")
          .tap(args => {
            return {
              name: "images/[name].[hash:8].[ext]"}; }); }, configureWebpack: { resolve:{alias: {"@_src": path.resolve(__dirname,"src/")}}}}Copy the code

Env Specifies the environment variable

  • Env file in the root directory, you can set environment variables (can set more than one)

    • Such as.env.producitonand.env.development
  • Global variables must start with VUE_APP except reserved NODE_ENV and BASE_URL.

    • Such asVUE_APP_MODE=beta
  • Note:.env does not allow comments

VUE_APP_MODE=production /** *.envCopy the code

Modular use of Store

With store modularization and route guard, different configurations of different routes can be realized on the page. For example, specific routes need to display different styles, and specific routes do not need headers or side navigation bars. Route guard can be configured in router.js, and each attribute can be defined by store. Get the configuration through mapState before instantiation to achieve the effect of different routes with different styles

Modularity of Store

->@_src/store/index.js

// @_src/store/index.js

import Vuex from "vuex";
import Vue from "vue";

import index from "./index/index.js";
import user from "./user";
Vue.use(Vuex);
const stores = {
  "index": index,
  user,
};

export const storeCreator = (moduleNames) => {
  const names = Array.isArray(moduleNames) ? moduleNames : [moduleNames];
  const modules = names.reduce((all, name) => {
    if (stores[name]) {
      all[name] = stores[name];
    }
    return all;
  }, {});

  returnnew Vuex.Store({ modules: { ... modules } }); };Copy the code

Store is introduced in each instance

->@_src/pages/index/store.js

import { storeCreator} from "@_src/store"

export default storeCreator(["index"."user"])
Copy the code

Store modularity works with route guard to implement style configuration of different routes

  • router.js
import Vue from "vue"
import VueRouter from "vue-router"
import store from "./store";

exportConst routes = [// initial access redirection to parent general transaction page {path:"/",
    redirect: "/a-menu",
    name: "home"
  },
  {
    name: "A menu",
    path: "/a-menu",
    component: () => import("./pages/amenu/index.vue"),
    meta: { title: "A menu",icon:"xxx", menuCode: "xxx"}
  },
  {
    name: Menu "B",
    path: "/b-menu",
    component: () => import("./pages/bmenu/index.vue"),
    meta: { title: "A menu",icon:"xxx", menuCode: "xxx"}},] // Header title color is white route const writeTitleRoutes = [{path:"/b-menu",
    name: Menu "B",},]; Vue.use(VueRouter); const router = new VueRouter({ routes }); // Configure router navigation. BeforeEach ((to,from,next)=>{let writeTitle=false
  for(leti=0; i<writeTitleRoutes.length; i++){ const pathReg = new RegExp(writeTitleRoutes[i].path);if (pathReg.test(to.path)) {
      writeTitle = true;
      break; }}if(store.state.index.writeTitle ! == writeTitle) { store.commit("index/SET_TITLE", writeTitle);
  }
  next();
})

export default router;
Copy the code