Vue中import from的来源--省略后缀与加载文件夹

Vue使用import ... from ...来导入组件,库,变量等。而from后的来源能够是js,vue,json。这个是在webpack.base.conf.js中设置的:

module.exports = {
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      '@': resolve('src')
    }
  }
...
}

这里的extensions指定了from后可导入的文件类型。vue

而上面定义的这3类可导入文件,js和vue是能够省略后缀的:webpack

import test from './test.vue'web

等同于:json

import test from './test'ide

同理:.net

import test from './test.js'code

等同于:component

import test from './test'blog

json不能够省略后缀:源码

import test from './test.json'

省略为:

import test from './test'

则编译出错。

那么,若test.vue,test.js同时存在于同一个文件夹下,则import的导入优先级是:

js>vue

from后的来源除了文件,还能够是文件夹:

import test from './components'

该状况下的逻辑是:

if(package.json存在 && package.main字段存在 && package.main指定的js存在) {
    取package.main指定的js做为from的来源,即便该js可能格式或内容错误
} else if(index.js存在){
    取index.js做为from的来源
} else {
    取index.vue做为from的来源
}

所以若from的来源是文件夹,那么在package.json存在且设置正确的状况下,会默认加载package.json;若不知足,则加载index.js;若不知足,则加载index.vue。

注意加载文件夹的形式,与上面省略后缀的形式是彻底相同的。因此一个省略后缀的from来源,有多是.vue,.js,或者文件夹。

例:

查看Vue-Element-Admin的源码,其中有个Layout.vue:

20181102164039187

里面调用import导入了3个组件:

import { Navbar, Sidebar, AppMain } from './components'

这里,from的路径'./components'就是个文件夹。

因而,按照前面的规则,首先查看文件夹下是否有package.json:

20181102164039207

并无package.json。

package.json不存在,那么查找index.js。index.js是存在的,因而加载。

打开index.js:

export { default as Navbar } from './Navbar'

export { default as Sidebar } from './Sidebar'

export { default as AppMain } from './AppMain'

能够看到3个export,都没有后缀,因此其类型vue,js和文件夹都是有可能的。

同一级目录下,存在AppMain.vue和Navbar.vue,没有同名js,因此能够判断出这两个都是加载的vue文件,即:

export { default as Navbar } from './Navbar.vue'

export { default as AppMain } from './AppMain.vue'

而Sidebar只有一个文件夹,因此是加载的文件夹。打开Sidebar文件夹:

优先找package.json。不存在。

而后找index.js,不存在。

最后找index.vue,存在。

因而:

export { default as Sidebar } from './Sidebar'

至关于:

export { default as Sidebar } from './Sidebar/index.vue'

这样,Layout.vue就经过加载一个文件夹,得到了3个vue组件。

站在巨人的肩膀上摘苹果:

原文:https://blog.csdn.net/fyyyr/article/details/83657828

相关文章
相关标签/搜索