2015-10-15 15 views
7

Come posso compilare il mio codice con webpack e babel in modo che la funzione esportata sia disponibile nell'ambito globale.Come esporre una funzione esportata in ambito globale con babel e webpack

Così, per esempio:

export function test(){console.log('test')} 

dovrebbe essere disponibile sotto window.test().

Quando ho appena eseguito babel -d ho ottenuto quello che mi aspetto:

'use strict'; 

Object.defineProperty(exports, '__esModule', { 
    value: true 
}); 
exports.test = test; 

function test() { 
    console.log('test'); 
} 

ma l'uscita webpack assomiglia a questo:

!function(e) { 
    function t(r) { 
    if (o[r])return o[r].exports; 
    var n = o[r] = {exports: {}, id: r, loaded: !1}; 
    return e[r].call(n.exports, n, n.exports, t), n.loaded = !0, n.exports 
    } 

    var o = {}; 
    return t.m = e, t.c = o, t.p = "", t(0) 
}([function(e, t) { 
    "use strict"; 
    function o() { 
    console.log("test") 
    } 

    Object.defineProperty(t, "__esModule", {value: !0}), t.test = o 
}]); 

terminare la funzione di test non è disponibile in ambito globale.

+0

Qualsiasi aggiornamento su questo? Ho cercato di imparare a fare lo stesso per un po 'di tempo. –

+0

Sto cercando di fare lo stesso, solo creare dinamicamente finestre/globali. Expose-loader funziona, ma si interrompe quando è necessario esporre un TON di globali – user1828780

risposta

0

check-out: https://webpack.github.io/docs/library-and-externals.html#examples

Impostando la proprietà uscita biblioteca a qualsiasi nome che si desidera avvolgere le variabili globali permetterebbero di allora chiamare: YourLibrary .test();

module.exports = { 
    entry: ['./_js/script.js'], 
    output: { 
     library: 'YourLibrary', 
     path: __dirname, 
     filename: './build/script.js' 
    } 
+4

ma come esportare solo una funzione –

+0

nell'esempio sopra si intende semplicemente chiamando 'YourLibrary()' come una funzione, non sono sicuro se questo è possibile Puoi comunque esporre/esportare una singola funzione, ad esempio, esporta la funzione 'foo() {...', quindi chiama 'YourLibrary.foo()' – glued

+1

sì, ma ho bisogno di chiamare le funzioni in un altro modulo esportato in 'YourLibrary. foo() ' –

Problemi correlati