Vue动态加载异步组件的方法

目前我们项目都是按组件划分的,然后各个组件之间封装成产品。目前都是采用iframe直接嵌套页面。项目中我们还是会碰到一些通用的组件跟业务之间有通信,这种情况下iframe并不是最好的选择,iframe存在跨域的问题,当然是postMessage还是可以通信的,但也并非是最好的。目前有这么一个场景:门户需要制作通用的首页和数据概览页面,首页和数据概览页面通过小部件来自由拼接。业务组件在制作的时候只需要提供各个模块小部件的url就可以了,可是如果小部件之间还存在联系呢?那么iframe是不好的。目前采用Vue动态加载异步组件的方式来实现小组件之间的通信。当然门户也要提供一个通信的基线:Vue事件总线(空的Vue实例对象)。

内容:

使用过vue的都应该知道vue的动态加载组件components:

Vue通过is来绑定需要加载的组件。那么我们现在需要的就是如何打包组件,如果通过复制业务组件内部的代码,那么这种就需要把依赖全部找齐,并复制过去(很多情况下会漏下某个图片或css等),这种方式是比较low的,不方便维护。因此我们需要通过webpack来打包单个vue文件成js,这边一个vue打包成一个js,不需压代码分割,css分离。因为component加载时只需要加载一个文件即可。打包文件配置如下:

首先在package.json加入打包命令:

"scripts": { ... "build-outCMP": "node build/build-out-components.js" },

Build-out-components.js文件:

'use strict' require('./check-versions')() process.env.NODE_ENV = 'production' const ora = require('ora') const path = require('path') const chalk = require('chalk') const webpack = require('webpack') const webpackConfig = require('./webpack.out-components.prod.conf') const spinner = ora('building for sync-components...') spinner.start() webpack(webpackConfig, function (err, stats) { spinner.stop() if (err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '\n\n') if (stats.hasErrors()) { console.log(chalk.red(' Build failed with errors.\n')) process.exit(1) } console.log(chalk.cyan(' Build complete.\n')) console.log(chalk.yellow( ' Tip: built files are meant to be served over an HTTP server.\n' + ' Opening index.html over file:// won\'t work.\n' )) })

webpack.out-components.prod.conf.js文件配置如下

const webpack = require('webpack'); const path = require('path'); const utils = require('./utils'); const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') const {entry, mkdirsSync} = require('./out-components-tools') function resolve(dir) { return path.join(__dirname, '..', dir) } mkdirsSync(resolve('/static/outComponents')) module.exports = { entry: entry, output: { path: resolve('/static/outComponents'), filename: '[name].js', }, resolve: { extensions: ['.js', '.vue', '.json'], alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src'), } }, externals: { vue: 'vue', axios: 'axios' }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { esModule: false, // vue-loader v13 更新 默认值为 true v12及之前版本为 false, 此项配置影响 vue 自身异步组件写法以及 webpack 打包结果 loaders: utils.cssLoaders({ sourceMap: true, extract: false // css 不做提取 }), transformToRequire: { video: 'src', source: 'src', img: 'src', image: 'xlink:href' } } }, { test: /\.js$/, loader: 'babel-loader', include: [resolve('src'), resolve('test')] }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, { test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('media/[name].[hash:7].[ext]') } }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' }), // UglifyJs do not support ES6+, you can also use babel-minify for better treeshaking: https://github.com/babel/minify new webpack.optimize.UglifyJsPlugin({ compress: false, sourceMap: true }), // Compress extracted CSS. We are using this plugin so that possible // duplicated CSS from different components can be deduped. new OptimizeCSSPlugin({ cssProcessorOptions: { safe: true } }) ] };

out-components-tools.js文件配置如下:

const glob = require('glob') const fs = require('fs'); const path = require('path'); // 遍历要打包的组件 let entry = {} var moduleSrcArray = glob.sync('./src/out-components/*') for(var x in moduleSrcArray){ let fileName = (moduleSrcArray[x].split('https://www.jb51.net/')[3]).slice(0, -4) entry[fileName] = moduleSrcArray[x] } // 清理文件 function mkdirsSync(dirname) { if (fs.existsSync(dirname)) { deleteall(dirname) return true; } else { if (mkdirsSync(path.dirname(dirname))) { fs.mkdirSync(dirname); return true; } } } // 删除文件下的文件 function deleteall(path) { var files = []; if(fs.existsSync(path)) { files = fs.readdirSync(path); files.forEach(function(file, index) { var curPath = path + "https://www.jb51.net/" + file; if(fs.statSync(curPath).isDirectory()) { // recurse deleteall(curPath); } else { // delete file fs.unlinkSync(curPath); } }); } }; exports.entry = entry exports.mkdirsSync = mkdirsSync

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/9bd2ac81a1cb06a83d7179d55cbce5bc.html