安裝和初始化 #
我們需要在命令行中安裝 vue-cli 工具客年,你可能還需要安裝 yarn。
$ npm install -g @vue/cli
# OR
$ yarn global add @vue/cli
然后新建一個項目。
$ vue create antd-demo
并配置項目魂爪。
工具會自動初始化一個腳手架并安裝 Vue 項目的各種必要依賴,如果在過程中出現(xiàn)網(wǎng)絡(luò)問題艰管,請嘗試配置代理或使用其他 npm registry滓侍。
然后我們進(jìn)入項目并啟動。
$ cd antd-demo
$ npm run serve
此時瀏覽器會訪問 http://localhost:8080/ 牲芋,看到 Welcome to Your Vue.js App
的界面就算成功了撩笆。
引入 antd #
這是 vue-cli 生成的默認(rèn)目錄結(jié)構(gòu)捺球。
├── README.md
├── babel.config
├── package.json
├── public
│ ├── favicon.ico
│ └── index.html
├── src
│ ├── assets
│ │ └── logo.png
│ ├── components
│ │ └── HelloWorld.vue
│ ├── App.vue
│ └── main.js
└── yarn.lock
現(xiàn)在從 yarn 或 npm 安裝并引入 ant-design-vue。
$ yarn add ant-design-vue
修改 src/main.js
夕冲,引入 antd 的按鈕組件以及全部樣式文件氮兵。
import Vue from "vue";
import Button from "ant-design-vue/lib/button";
import "ant-design-vue/dist/antd.css";
import App from "./App";
Vue.component(Button.name, Button);
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount("#app");
修改 src/App.vue
的 template 內(nèi)容。
<template>
<div id="app">
<img src="./assets/logo.png">
<a-button type="primary">Button></a-button>
</div>
</template>
...
好了歹鱼,現(xiàn)在你應(yīng)該能看到頁面上已經(jīng)有了 antd 的藍(lán)色按鈕組件泣栈,接下來就可以繼續(xù)選用其他組件開發(fā)應(yīng)用了。其他開發(fā)流程你可以參考 vue-cli 的官方文檔弥姻。
高級配置 #
我們現(xiàn)在已經(jīng)把組件成功運行起來了南片,但是在實際開發(fā)過程中還有很多問題,例如上面的例子實際上加載了全部的 antd 組件的樣式(對前端性能是個隱患)庭敦。
此時我們需要對 vue-cli 的默認(rèn)配置進(jìn)行自定義疼进。
使用 babel-plugin-import #
babel-plugin-import 是一個用于按需加載組件代碼和樣式的 babel 插件(原理)。
$ yarn add babel-plugin-import --dev
使用 vue-cli 2 的小伙伴 #
修改.babelrc
文件秧廉,配置 babel-plugin-import
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
- "plugins": ["transform-vue-jsx", "transform-runtime"]
+ "plugins": [
+ "transform-vue-jsx",
+ "transform-runtime",
+ ["import", { "libraryName": "ant-design-vue", "libraryDirectory": "es", "style": "css" }]
+ ]
}
使用 vue-cli 3 的小伙伴 #
修改babel.config.js
文件颠悬,配置 babel-plugin-import
module.exports = {
presets: ["@vue/app"],
+ plugins: [
+ [
+ "import",
+ { libraryName: "ant-design-vue", libraryDirectory: "es", style: true }
+ ]
+ ]
};
然后移除前面在 src/main.js
里全量添加的 import 'ant-design-vue/dist/antd.css';
樣式代碼,并且按下面的格式引入模塊定血。
// src/main.js
import Vue from 'vue'
- import Button from 'ant-design-vue/lib/button';
+ import { Button } from 'ant-design-vue';
- import 'ant-design-vue/dist/antd.css'
import App from './App'
Vue.component(Button.name, Button)
Vue.config.productionTip = false
new Vue({
render: h => h(App)
}).$mount("#app");
最后重啟 npm run serve
訪問頁面赔癌,antd 組件的 js 和 css 代碼都會按需加載,你在控制臺也不會看到這樣的警告信息澜沟。關(guān)于按需加載的原理和其他方式可以閱讀這里灾票。