require后面不加default會報錯


在項目中用 require('./Download.vue') 引入一個組件的時缺少.default 會報錯:

Failed to mount component: template or render function not defined

<template>
  <div id="app">
    <Download />
  </div>
</template>
<script type="application/javascript">
   let Download = require('./Download.vue').default

export default {
  name: 'app',
  components: {
    Download
  }
}
</script>

而有的時候不加.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 來獲取。

 

借鑒:https://leotian.cn/posts/7a8a/

   https://www.cnblogs.com/caiguangbi-53/p/11757508.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM