vue动态路由配置, 通过路由区分模块化打包配置

3 篇文章 0 订阅
import Vue from 'vue';
import Router from 'vue-router';
import config from '@/config';

Vue.use(Router);

// 模块路由名称(与文件夹名称相同)
const moduleNameList = [
  "basicService",
  "equipment",
  "upkeep",
  "workOrderRouter",
  "medicalWaste",
  "inspection",
  "orderResource",
  "taskCode",
  "warehouse",
  "clientRelation",
  "transport",
  "construction"
];
// 动态路由
export const asyncRoutes = [];

// 固定路由
export const constantRoutes = [
  // {
  //   name: "index",
  //   path: "/",
  //   component: () => import("@/views/index")
  // }
]

const createRouter = () => new Router({
  // mode: 'history', // require service support
  linkActiveClass: 'active',
  routes: [].concat(constantRoutes, asyncRoutes)
})

// router 
const router = createRouter();

// 配置的模块
const modules = config.modules;

function genAsyncRoutes(mList) {
  let count = mList.length;
  mList.forEach(moduleName => {
    if (moduleNameList.includes(moduleName)) {
        import(`./${moduleName}/${moduleName}`).then(route => {
          route.default.forEach(val =>{
            asyncRoutes.push(val);
          })
          if (--count === 0) {
            router.addRoutes(asyncRoutes);
          }
        });
    }
  });
}

// 处理模块
function disposeModules() {
    if (typeof modules === 'string') {
      if (modules === 'all') {
        genAsyncRoutes(moduleNameList);
      } else if (moduleNameList.includes(modules)) {
        genAsyncRoutes([modules]);
      }
    } else if (modules instanceof RegExp) {
      genAsyncRoutes(moduleNameList.filter(name => modules.test(name)));

    } else if (modules instanceof Array) {
      genAsyncRoutes(modules);
    }
}
disposeModules();

config.js 里面加个配置 modules:‘all’ 来控制

module.exports =  {
 target: '210', // 生产 production  测试 205 ,208
 debug: true,
 timeout: 100000,
 userInfo: null,
 modules:'medicalWaste' // 模块区分打包配置 对应路由模块的文件夹名称,all 表示全量打包 ["basicService","medicalWaste"]
}

vue.config.js

'use strict'
const webpack = require('webpack')
const path = require('path')
const fs = require('fs')
const config = require('./src/config')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = 'vue project' // page title
// const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin'); // 骨架屏引入
// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
const port = 8081 // dev port
const HtmlWebpackPlugin = require('html-webpack-plugin') // 引入CDN配置插件
const externals = { // 不打包插件
  // vue: 'Vue',
  // 'vue-router': 'VueRouter',
  // vuex: 'Vuex',
  // axios: 'axios',
  // 'element-ui': 'ElementUI',
  // vconsole:'vConsole', // 生产打包放开
  moment: 'moment',
  echarts: 'echarts'
}
const cdn = {
  // 开发环境
  dev: {
    css: [

    ],
    js: [

    ]
  },
  // 生产环境 配置对应CDN地址
  build: {
    css: [
      // 'https://cdn.bootcdn.net/ajax/libs/element-ui/2.5.4/theme-chalk/index.css'
    ],
    js: [
      // 'https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.min.js',
      // 'https://cdn.bootcss.com/vue-router/3.0.6/vue-router.min.js',
      // 'https://cdn.bootcss.com/vuex/3.1.0/vuex.min.js',
      // 'https://cdn.bootcss.com/axios/0.19.0/axios.min.js',
      'https://cdn.bootcdn.net/ajax/libs/moment.js/2.23.0/moment.min.js',
      'https://cdn.bootcdn.net/ajax/libs/echarts/4.2.1/echarts.min.js'
    ]
  }
}

function genIgnoreReg(all,list){
  let idx;
  list.forEach(module =>{
    idx = all.indexOf(module);
    if(idx !== -1) all.splice(idx,1); 
  })
  return new RegExp(`(${all.join('|').replace(/\|$/,'')})`);
}

const routeList = fs.readdirSync('./src/router');

// 动态打包模块
const modules = config.modules;
let ignoreReg = null;
if (typeof modules === 'string') {
  if (modules !== 'all') {
    ignoreReg = genIgnoreReg(routeList,[modules]);
  } 
} else if (modules instanceof Array) {
  ignoreReg = genIgnoreReg(routeList,modules);
}
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {

  // 205 || 生产
  // publicPath: '/web/vue/',
  runtimeCompiler: true, // 运行时报错配置
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  // eslint-loader是否在保存的时候检查
  lintOnSave: false,
  // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
  productionSourceMap: false,
  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    // 跨域代理
    proxy: {
      "/api": {
        target: 'http://192.168.1.70:7979',
        changeOrigin: true, // 是否改变域名
        ws: true
        // pathRewrite: {
        //   // 路径重写
        //   "/api": "" // 这个意思就是以api开头的,定向到哪里, 如果你的后边还有路径的话, 会自动拼接上
        // }
      }
    }
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        '@': resolve('./src'),
        'assets': resolve('./src/assets'),
        'style': resolve('./src/style')
      }
    },
    plugins:ignoreReg ? [ new webpack.IgnorePlugin(ignoreReg,/router$/)] : undefined,
    externals: process.env.NODE_ENV === 'production' ? externals: {}
  },
  css: {
      extract: true, // css拆分ExtractTextPlugin插件,默认true - 骨架屏需要为true
      loaderOptions: {
          postcss: {
              plugins: [
                  require('postcss-plugin-px2rem')({
                      rootValue: 46, //换算基数, 默认100  ,这样的话把根标签的字体规定为1rem为50px,这样就可以从设计稿上量出多少个px直接在代码中写多上px了。
                      // unitPrecision: 5, //允许REM单位增长到的十进制数字。
                      //propWhiteList: [],  //默认值是一个空数组,这意味着禁用白名单并启用所有属性。
                      // propBlackList: [], //黑名单
                      exclude: /(node_module)/,  //默认false,可以(reg)利用正则表达式排除某些文件夹的方法,例如/(node_module)/ 。如果想把前端UI框架内的px也转换成rem,请把此属性设为默认值
      // selectorBlackList: [], //要忽略并保留为px的选择器
                      // ignoreIdentifier: false,  //(boolean/string)忽略单个属性的方法,启用ignoreidentifier后,replace将自动设置为true。
                      // replace: true, // (布尔值)替换包含REM的规则,而不是添加回退。
                      mediaQuery: false,  //(布尔值)允许在媒体查询中转换px。
                      minPixelValue: 0 //设置要替换的最小像素值(3px会被转rem)。 默认 0
                  }),
              ]
          }
      }
  },
  chainWebpack: config => {
      // config.entry.app = ['babel-polyfill', './src/main.js'];
      config.plugins.delete("preload"); // TODO: need test
      config.plugins.delete("prefetch"); // TODO: need test

      // 对vue-cli内部的 webpack 配置进行更细粒度的修改
      config.plugin('html').tap(args => {
        if (process.env.NODE_ENV === 'production') {
            args[0].cdn = cdn.build
        }
        if (process.env.NODE_ENV === 'development') {
            args[0].cdn = cdn.dev
        }
        return args
    })
    config.module
    .rule('images')
      .use('url-loader')
        .loader('url-loader')
        .tap(options => Object.assign(options, { limit: 2000, esModule: false })); // 配置线上图片转base64。 app 已有做浏览器缓存。转换过大,会加大首屏加载时长

      // set svg-sprite-loader
      // config.entry('main').add('babel-polyfill');
      config.module
      .rule('iview')
      .test(/iview.src.*?js$/)
      .use('babel')
        .loader('babel-loader')
        .end();

      config.module
        .rule("svg")
        .exclude.add(resolve("src/icons"))
        .end();
      config.module
        .rule("icons")
        .test(/\.svg$/)
        .include.add(resolve("src/icons"))
        .end()
        .use("svg-sprite-loader")
        .loader("svg-sprite-loader")
        .options({
          symbolId: "icon-[name]"
        })
        .end();

      // set preserveWhitespace
      config.module
        .rule("vue")
        .use("vue-loader")
        .loader("vue-loader")
        .tap(options => {
          options.compilerOptions.preserveWhitespace = true;
          return options;
        })
        .end();

      config
      // https://webpack.js.org/configuration/devtool/#development
      .when(process.env.NODE_ENV === "development", config =>
        config.devtool("cheap-source-map")
      );

      config.when(process.env.NODE_ENV !== "development", config => {
        config
          .plugin("ScriptExtHtmlWebpackPlugin")
          .after("html")
          .use("script-ext-html-webpack-plugin", [
            {
              // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }
          ])
          .end();
        config.optimization.splitChunks({
          chunks: "all",
          cacheGroups: {
            libs: {
              name: "chunk-libs",
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
              chunks: "initial" // only package third parties that are initially dependent
            },
            // elementUI: {
            //   name: "chunk-elementUI", // 将elementUI拆分成一个包
            //   priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            //   test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // 以适应cnpm
            // },
            commons: {
              name: "chunk-commons",
              test: resolve("src/components"), // 可以自定义规则
              minChunks: 3, //  minimum common number
              priority: 5,
              reuseExistingChunk: true
            }
          }
        });
        config.optimization.runtimeChunk("single");
      });
  }
}              
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue.js是一种流行的JavaScript前端框架,可以用来构建现代化的Web应用程序。Vue框架提供的addroutes方法可以用来实现动态路由的功能。下面是一个使用Vue框架的addroutes方法来实现动态路由的示例: 首先,我们要在Vue项目中引入Vue Router模块,这样我们就可以使用Vue Router提供的路由功能了。可以通过npm安装Vue Router模块,并在项目中引入。 然后,在Vue项目的主页面(例如App.vue)中,可以创建一个按钮,并在点击按钮时,动态添加一个新的路由。例如: <template> <div> <button @click="addNewRoute">添加新路由</button> </div> </template> <script> export default { methods: { addNewRoute() { // 使用Vue Router提供的addroutes方法来添加新路由 this.$router.addRoutes([ { path: '/newroute', component: () => import('./NewRoute.vue') } ]); } } } </script> 在上面的示例中,我们在点击按钮时调用addNewRoute方法。该方法使用Vue Router的addroutes方法来添加一个新的路由对象。这里的新路由对象有两个属性:path(路径)和component(组件)。我们将新路由的路径设置为"/newroute",并将对应的组件设置为NewRoute.vue。 当我们点击按钮时,新路由将被添加到Vue Router中,并且可以在地址栏中访问到。例如,在地址栏中输入"/newroute",将会加载NewRoute.vue组件。 总而言之,Vue框架的addroutes方法可以用来实现动态路由的功能。通过在主页中监听按钮点击事件,并调用addroutes方法来添加新的路由对象,我们可以在Vue应用中实现动态路由的功能。以上就是一个简单的例子。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值