在项目中用 require('./Download.vue') 引入一个组件的时缺少.default 会报错:
Failed to mount component: template or render function not defined
name:'app',
components: {
Download
}
}
而有的时候不加.default也不会报错,这是怎么回事呢
babel可以把 import/export 转成node 的 module.exports/ require 。
但是Babel@6不再export default 的module.exports了。
如果一个模块中仅仅export default, 那么就不用加.default了。如果除此之外还有别的对象被 export 出来,那不好意思,只能老老实实写default 了。
解决方法:
'use strict';
Object.defineProperty(exports,"__esModule", {
value:true});
exports.default = 'foo';
module.exports= exports['default'];//调用时
require('./bundle.js') //foo
二,补充的知识点
首先 webpack 支持 CommonJS、AMD 和 ES6模块打包。当我们用 .vue 单文件写组件时,在 script 标签内使用的是 ES6 的语法且使用 export default 进行默认导出。然而,require 是 CommonJS 的模块导入方式,不支持模块的默认导出,因此导入的结果其实是一个含 default 属性的对象,因此需要使用 .default 来获取实际的组件,当然我们也可以使用 ES6 的 import 语句,如果使用 import,需要给定一个变量名,所有 import 语句必须统一放在模块的开头。相反,如果 .vue 文件中使用 CommonJS 或 AMD 模块化语法,使用 module.exports 对象进行导出,那么使用 require 导入时就不需要使用 .default 来获取。