更新时间:2024-04-19 GMT+08:00
分享

开发指导

AUI为内部开源使用,外部无法访问,底层逻辑使用Vue组件暴露封装,因此在不使用AUI情况下,通过原生Vue CLI脚手架搭建组件库形式暴露卡片组件,也能够正常使用。

开发过程

准备工作中已经正常安装了Vue CLI脚手架,因此可以快速搭建Vue项目。

  1. 初始化Vue项目。

    vue create my-app

    选择Vue3。

    图1 选择Vue3

  2. 运行项目。

    npm run serve
    图2 项目目录
    图3 访问页面

  3. 卡片封装,新建package文件夹。

    图4 新增package包

    添加样例组件DemoCard.vue,添加任意样例代码如下:

    <template>
        <div class="hello">
          <h1>我是卡片</h1>
          <img src="../assets/logo.png"/>
        </div>
      </template>
      <script>
      export default {
        name: 'DemoCard',
        props: {
          url: String  // url接收来自门户关于静态资源的路径
        }
      }
      </script>
      <!-- Add "scoped" attribute to limit CSS to this component only -->
      <style scoped>
      h3 {
        margin: 40px 0 0;
      }
      </style>

    然后我们引用到App.vue组件里面验证一下,看组件是否可用,代码如下:

    <template>
      <img alt="Vue logo" src="./assets/logo.png">
      <HelloWorld msg="Welcome to Your Vue.js App"/>
    </template>
    <script>
    import HelloWorld from './package/demoCard.vue'
    export default {
      name: 'App',
      components: {
        HelloWorld
      }
    }
    </script>
    <style>
    #app {
      font-family: Avenir, Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    </style>

    最终效果显示如下:

    图5 组件预览

  4. 使用Vue打包的lib库模式,添加入口文件。

    打包后的js文件运行逻辑已在门户专门处理,按照下列方式配置打包入口文件即可。

    在package目录下新建index.js文件,代码如下:

    import demoCard from './demoCard.vue'
    const compoent = {
        default: demoCard
    };
    export default compoent

  5. 打包配置。

    图6 vue.config.js 配置

    配置示例:

    const { defineConfig } = require('@vue/cli-service')
    module.exports = defineConfig({
      transpileDependencies: true,
      css: { extract: false },
      configureWebpack: {
        output: {
          libraryExport: 'default'
        },
        optimization: {
          splitChunks: false
        },
        externals: {
          'vue': 'vue'
        }
      },
    })

  6. 卡片打包。

    到这里为止,我们的卡片封装基本就完成了,当然卡片封装成什么样得看自己的业务需求了,接下来我们就需要将卡片进行打包了。

    修改我们项目的package.json文件,配置打包命令:

    "build-lib": "vue-cli-service build --target lib --name mylib --dest lib src/package/index.js"
    图7 npm命令

    打包命令解释:

    • --target lib 关键字指定打包的目录。
    • --name 打包后的文件名字。
    • --dest 打包后的文件夹的名称。

    然后执行打包命令:

    npm run build-lib

    打包执行完成后我们项目目录下就会多出一个“lib”文件夹,存放的是打包后的文件。

    图8 输出件

分享:

    相关文档

    相关产品