zoukankan      html  css  js  c++  java
  • 如何利用 babel-plugin-import 解决vue自定义组件库组件按需加载以及对应组件样式按需加载?

      经常使用vue开源UI组件库,如iview,Element,Vant等。于是自己尝试借助vue-cli4搭建vue组件库。如何搭建vue组件库以及npm发布组件库网上的软文很多,就不详细介绍搭建过程。在借鉴网上一些搭建过程中,发现大多数案例其实没有实现组件的按需加载,有的样式还需要手动按需引入;如何解决这个问题?

      解决这个问题使用到了 babel-plugin-import 依赖,对于babel-plugin-import依赖的安装与介绍详见https://www.npmjs.com/package/babel-plugin-import

      假设项目中要使用的组件:import { Switch } from "v-easyui123";

      对于babel-plugin-import配置,按照介绍资料,babel.config.js配置多种情况如下:

        配置一:{ "libraryName": "v-easyui123", style: "css" }应该等价于:

            var switch = require('v-easyui123/lib/switch');

            require('v-easyui123/lib/switch/style/css');

        配置二:{ "libraryName": "v-easyui123", style: true } 应该等价于:

            var switch = require('v-easyui123/lib/switch');

            require('v-easyui123/lib/switch/style');

        对于上面两种配置,组件都能按需引入,但是对应组件的样式即使更改成对应的解析路径都不能引入成功,那么到底如何解决呢?

        对于样式的加载,官网上还有这么一段话:If option style is a Function, babel-plugin-import will auto import the file which filepath equal to the function return value. This is useful for the components library developers。

        大概意思就是如果属性style是一个函数,那么babel-plugin-import会自动导入函数返回值的文件,看v-easyui123依赖目录:

          

     对应的配置文件如下: 

    module.exports = {
      presets: [
        '@vue/cli-plugin-babel/preset'
      ],
      plugins: [
        [
          "import",
          {
            libraryName: "v-easyui123",
            style: (name) => {
              console.log('style-->>', name)
              // v-easyui123/lib/switch/index.js
              // 注意这里的name为组件所在的路径,按需加载样式配置提取对应组件名称的css即可
              return `v-easyui123/lib/style/${name.split('/')[2]}.css`
            },
            customName: (name) => {
              console.log('customName-->>', name) //switch
              return `v-easyui123/lib/${name}/index.js`
            }
          }
        ]
      ]
    }

      注意此配置中属性style与customName函数中参数的含义  

      当项目中引入 import { Switch } from "v-easyui123";对于上面配置等价于: 

       var switch = require('v-easyui123/lib/switch');

       require('v-easyui123/lib/switch/style/switch.css');

      到此自定义组件库样式按需加载就搞定了

  • 相关阅读:
    姐姐的vue(1)
    LeetCode 64. Minimum Path Sum 20170515
    LeetCode 56. 56. Merge Intervals 20170508
    LeetCode 26. Remove Duplicates from Sorted Array
    LeetCode 24. Swap Nodes in Pairs 20170424
    LeetCode 19. Remove Nth Node From End of List 20170417
    LeetCode No.9 Palindrome Number 20170410
    LeetCode No.8. String to Integer (atoi) 2017/4/10(补上一周)
    LeetCode No.7 Reverse Integer 2017/3/27
    LeetCode No.4 Median of Two Sorted Arrays 20170319
  • 原文地址:https://www.cnblogs.com/changxue/p/13439184.html
Copyright © 2011-2022 走看看