簡體   English   中英

Module.exports 和 es6 導入

[英]Module.exports and es6 Import

與 babel 反應。 我對導入和 module.exports 有這種困惑。 我假設 babel 在將 ES6 代碼轉換為 ES5 時將導入和導出分別轉換為 require 和 module.exports。

如果我從一個模塊導出一個函數並在另一個模塊中導入該函數,則代碼執行正常。 但是,如果我使用 module.exports 導出函數並使用“import”導入,則會在運行時拋出錯誤,表示它不是函數。

我編了一個例子。

// Tiger.js
function Tiger() {
    function roar(terrian){
        console.log('Hey i am in ' +  terrian + ' and i am roaing');
    };
    return roar;
}

module.exports = Tiger;

// animal.js
import { Tiger } from './animals';

var animal = Tiger();
animal("jungle");

我使用帶有預設 es2015 的 babel 來編譯它。 這給了我以下錯誤

Uncaught TypeError: (0 , _animals.Tiger) 不是函數

但是如果我刪除module.exports = Tiger; 並將其替換為export { Tiger }; 它工作正常。

我在這里錯過了什么?

編輯:我使用 browserify 作為模塊捆綁器。

export { Tiger }等價於module.exports.Tiger = Tiger

相反, module.exports = Tiger等同於export default Tiger

因此,當您使用module.exports = Tiger然后嘗試import { Tiger } from './animals'您實際上是在要求Tiger.Tiger

如果您想導入:

module.exports = Tiger

您可以使用以下結構:

import * as Tiger from './animals'

然后它會起作用。

另一種選擇是按照@Matt Molnar 的描述更改導出,但只有當您是導入代碼的作者時才有可能。

module.exports未設置時,它指向一個空對象 ( {} )。 當您執行module.exports = Tiger ,您是在告訴運行時從該模塊導出的對象是Tiger對象(而不是默認的{} ),在這種情況下它是一個函數。
由於您想導入相同的函數,導入的方式是使用默認導入( import tiger from './tiger' )。 否則,如果您想使用命名導入( import { tiger } from './tiger' ),您必須更改module.exports對象或使用export關鍵字而不是module.exports對象。

默認導入/導出:

// tiger.js
module.exports = tiger;
// or
export default function tiger() { ... }

// animal.js
import tiger from './tiger';

命名導入/導出:

// tiger.js
module.exports = { tiger };
// or
module.exports.tiger = tiger
// or
export const tiger = () => { ... }
// or
export function tiger() => { ... }

// animal.js
import { tiger } from './tiger';

對我來說,我正在嘗試將其應用於webpack.config.ts。 以上內容不能import * as X from "./X"; 我收到另一個錯誤。

Module.exports,帶有es6導入,用於typescript中的webpack.config.ts

在此輸入圖像描述

const getConfig = ( appDir: string, distDir: string, env: any, args: any ): webpack.Configuration => {
    const config: webpack.Configuration = {
        return config;
    };
};

module.exports = getConfig;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM