zoukankan      html  css  js  c++  java
  • 单页面和多页面续集

    单页面和多页面续集

    一、组件化模块化

    上集说到,我们希望views专注页面渲染

    我们将组件拆分出去,相对应的我们还可以将样式代码,api请求等拆分,按需引入。

    一、目录结构

    |_src
    	|_assets
    		|_js
    			|_scanCompontent.js  //webpack方法处理过多的import 引入
    	|_api
    		|_apilist.js
    		|_axios.js
    	|_router
    		|_index.js
    	|_styles
    		|_home
    			|_index.scss
    		|_about	
    			|_index.scss
    	|_instance
    		|_home
    			|_index.vue
    			|_main.js
    		|_about
    			|_index.vue
    			|_main.js
    	|_components
    		|_home
    			|_one.vue
    			|_two.vue
    		|_about
    			|_about.vue
    	|_views
    		|_home.vue
    		|_about.vue
    

    二、方法介绍

    webpack优化之一
    
    main.js
    require.context(dir,boolean, reg)
    				文件夹路径,是否搜索子目录,匹配文件的正则
    				
    我们可以使用它遍历自定义封装的组件,循环注册成全局组件,我们就可以不用一一import
    
    const files = require.context('@/components',true,/.vue$/)
    
    const modules = []     //modules在这别找不到了
    
    说明:
    	require.context()执行后files
    	返回一个函数webpackContext
    	ƒ webpackContext(req) {
    	var id = webpackContextResolve(req);
    	return __webpack_require__(id);
    }
    可以看到执行后又返回了一个__webpack_require__,这个__webpack_require__相当于require或者import,webpackContext还有第二个静态方法keys和resolve,一个id属性
    	我们着重看keys
    	试着输出console.log(files.keys())
    	输出是地址数组:["./four/Index.vue", "./one/alice.vue", "./one/bob.vue", "./one/cini.vue", "./one/deft.vue", "./three/Index.vue", "./two/Index.vue"]
    	这边你可能还是不知道获取到这些路径有什么用,我们继续来看
    	试着遍历这个数组
    	files.keys().forEach(ele=>{
    		console.log(ele); //不用说你也知道是一个个路径
    		试着将路径放到files中
    		console.log(files(ele))
    		输出:Module {default: {…}, __esModule: true, Symbol(Symbol.toStringTag): "Module"}
    		实际上这正是我们要引入的组件
    		让我们回想一下vue中怎么注册全局组件
    			Vue.component(name,con)
    		那么我们可以定义一个modules来存放这些将来成为全局组件的东东,暂时收留一下它们
    		
    		让我们对名字做一些处理
    		let name = key.split('/').pop().replace(/.vue/g,"");
    		let component = files(ele);
    		modules.push({name,component})
    	})
    	最后让我们看以后modules是什么样的?
    	0: {name: "Index", component: Module}
        1: {name: "alice", component: Module}
        2: {name: "bob", component: Module}
        3: {name: "cini", component: Module}
        4: {name: "deft", component: Module}
        5: {name: "Index", component: Module}
        6: {name: "Index", component: Module}
        length: 7
        __proto__: Array(0)
        
        有了这些我们就可以将它们注册为全局组件了
        modules.map(ele=>{
        	let {name,component:com} = ele
        	Vue.component(name,com.default)
        })
       	然后就是组件的使用了,就不多说了
       	<alice></alice>
      
      	实际上可以将这段代码引出去scanCompontent.js
    

    https://www.webpackjs.com/guides/dependency-management/

    二、多页面中涉及的到的webpack处理

    一、方法介绍

    glob

    npm i glob
    const glob = require('glob')
    glob("**/*.js",options,function(err,files){})
    
    entry.js
    let titles = {
    	a:xxx,
    	b:xxx
    }
    function getEntry(globPath){  //执行全局同步搜索
    	let entries = {}, tmp, htmls = {};
    	glob.sync(globPath+'js').forEach(function(entry) {
            tmp = entry.split('/').splice(-3);
            entries[tmp[1]] = {
                entry,
                template: 'index.html', 
                filename:tmp[1] + '.html',
                title:titles[tmp[1]]
            };
        });
        return entries;
    }
    let htmls = getEntry('./src/instance/**/*.');
     //  ' /**/* '
     // 包含instance下的所有目录的所有文件, 包含任何目录下面的目录下的文件
     
    module.exports = htmls
    
    
    cmd中输出
    {
      about: {
        entry: './src/instance/about/main.js',
        template: 'index.html',
        filename: 'about.html',
        title: undefined
      },
      home: {
        entry: './src/instance/home/main.js',
        template: 'index.html',
        filename: 'home.html',
        title: undefined
      }
    }
    

    externals

    externals 配置选项提供了「从输出的 bundle 中排除依赖」的方法。相反,所创建的 bundle 依赖于那些存在于用户环境(consumer's environment)中的依赖。

    防止将某些 import 的包(package)打包到 bundle 中,而是在运行时(runtime)再去从外部获取这些扩展依赖(external dependencies)

    index.html通过cdn的方式引入
    const externals = {
    	jquery:'Jquery'
    }
    module.exports = externals;
    

    plugins

    首先plugins的插件比较多,这边就简单介绍用到的

    compression-webpack-plugin

    压缩webpack 插件

    npm install compression-webpack-plugin --save-dev
    
    vue.config.js
    const CompressionPlugin = require('compression-webpack-plugin');
    module.exports = {
    	plugins:[new CompressionPlugin({
            filename: '[path].gz[query]',  文件名
            algorithm: 'gzip',  //压缩算法/功能
            test: /.(js|css|svg|woff|ttf|json|html)$/,  /Include all assets that pass test assertion
            threshold: 10240, //仅处理比10240字节大的插件
            minRatio: 0.8,  //仅压缩比该比率更好的资产
            deleteOriginalAssets: false  //是不是删除原来的origin assets
    	})],
    }
    
    uglifyjs-webpack-plugin

    js压缩

    npm install uglifyjs-webpack-plugin --save-dev
    
    module.exports = {
      optimization: {
        minimizer: [new UglifyJsPlugin()],
      },
    };
    

    二、vue中webpack设置

    调整webpack配置最简单的方法就是在vue.config.js中的configureWebpack选项提供一个对象:

    //vue.config.js
    module.exports = {
    	configureWebpack:{
    		plugins:[
    			new CompressionPlugin()
    		]
    	}
    }
    
    如果你需要基于环境有条件地配置行为,或者想要直接修改配置,那就换成一个函数 (该函数会在环境变量被设置之后懒执行)。该方法的第一个参数会收到已经解析好的配置。在函数内,你可以直接修改配置,或者返回一个将会被合并的对象:
    module.exports = {
    	configureWebpack:config=>{
             if (process.env.NODE_ENV === 'production') {
              // 为生产环境修改配置...
            } else {
              // 为开发环境修改配置...
            }
    	}
    }
    
    module.exports = {
        configureWebpack: (config) => {
            config.externals = externals;
            config.plugins = [...config.plugins,...plugins];
            config.optimization = optimization;
        },
        pages:htmls,
        publicPath: './',           
        outputDir: 'dist',        
        devServer: {
            open: true, 
            hot:true                
        }
      }
    
  • 相关阅读:
    php命令注入
    mysql事物
    安装php环境
    移除服务器缓存实例
    show user profile synchronization tools
    manual start user profile import
    JSON is undefined. Infopath Form People Picker in SharePoint 2013
    asp.net web 应用站点支持域账户登录
    Load sharepoint envirement by powershell
    sharepoint 2016 download
  • 原文地址:https://www.cnblogs.com/qjsbk/p/13777914.html
Copyright © 2011-2022 走看看