ant-design-vue 的按需加载

1,166 阅读1分钟

应该有很多人写过了但我还是自己写一下给自己做个记录。

vue creat demo

====> default 2

done!

npm i less less-loader -S

下载antdv

npm i ant-design-vue -D

下载babel-plugin-import

npm i babel-plugin-import -D

下载 vue/cli4生成的default vue2项目中,配置babel.config.js,antdv官网如下说到:

 module.exports = {
  presets: ["@vue/app"],
+  plugins: [
+    [
+      "import",
+      { libraryName: "ant-design-vue", libraryDirectory: "es", style: true }
+    ]
+  ]
};

但实际上style后面的true应该换为 "css",这个不要问原因,人插件要求这样配置的。

接下来完整导入按照官网文档即可,按需加载此时在main.js文件中,写入:

import Vue from 'vue'
import App from './App.vue'
+	import { Button } from 'ant-design-vue'

Vue.config.productionTip = false

+	Vue.use(Button)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

即可使用button组件了。另外也可以在单个组件中导入,但是在main中导入比较统一:

<template>
  <div class="hello">
    <Button>hello</Button>
  </div>
</template>

<script>
import { Button } from 'ant-design-vue'
export default {
  name: 'HelloWorld',
  components: {
    Button
  }
}
</script>

不知道为什么,在下载的npm i 参数选择-S时,以上操作会报错,antd无法按需加载,只知道-S是在package.json的dependencies中添加,-D则是在devDenpendencies中添加。


我知道为什么会出现上面的错误了,原因不是-S或-D,而是下载了babel-plugin-import,使用了这个以后,会将import的路径变更至antdv的lib目录中,而antd是在antdv的dist目录下,lib中是每个组件,而dist是完整项目,一旦使用babel-plugin-import还想完整引入,则会报在lib目录下找不到antd或者你起的随便的一个名字的错误。