项目在使用iView 插件的时候,官方推荐,配置一下 .babelrc 文件,使用 babel 插件 babel-plugin-import 来实现按需加载组件。
首先,如果我们不使用babel-plugin-import 插件的时候,使用iView 方式。如下。是在全局的 main.js 中代码,引入iview。
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import iView from 'iview'
import 'iview/dist/styles/iview.css'
Vue.config.productionTip = false
Vue.use(iView)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
然后在使用插件的地方,引入一下那个组件。如下。
<template>
<div>Hello world!
<Button type="primary">Primary</Button>
</div>
</template>
<script>
import { Button } from 'iview'
export default {
name: 'TimePicker',
components: {
'Button': Button
}
}
</script>
<style scoped>
</style>
这样才可以。那我们使用了 babel-plugin-import 之后。就很简单了,首先,我们要配置一下 .babelrc 文件。下面是iView 官网中的配置。
下面,我们就按照它给的配置,写一下我们的 .babelrc 文件,如下。我们的文件之前已经有了两个 plugin 了。
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": [
"transform-vue-jsx",
"transform-runtime",
["import", {
"libraryName": "iview",
"libraryDirectory": "src/components"
}]
]
}
然后,我们的main.js 就可以不引入 iview 了,之要加入样式就行。如下。
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
// import iView from 'iview'
import 'iview/dist/styles/iview.css'
Vue.config.productionTip = false
// Vue.use(iView)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
然后,我们在使用iView 的地方,直接引入,如下。
<template>
<div>Hello world!
<Button type="primary">Primary</Button>
</div>
</template>
<script>
import { Button } from 'iview'
export default {
name: 'TimePicker',
components: {
'Button': Button
}
}
</script>
<style scoped>
</style>