javascriptwebpackjint

Export global function using webpack


I'm trying to write an isomorphic module. The server javascript is going to run inside of JINT. I have created a webpack bundle specifically to build the server version of the module. I want to expose a single function that I can get JINT to call. I am using the scriptEngine.Invoke function from JINT however this is looking for a function on the global object. I don't know how to get a function onto the global object. I have tried using the expose-loader but this seems to export the entire module and I can't get it to just expose a single function.

Here is my entry point:

require("expose?FormValidator!./formValidator.js");

Here is my formValidator.js:

export default function validate () {
    return 'HelloWorld';
}

When I load up the resulting bundle and examine the FormValidator global it is an object with a validate function. Is there a way I can get the validate function to be directly assigned to FormValidator?


Solution

  • I am in the same situation as you do.Here is my code:

    webpack.config.js:

    module.exports = {
        entry: './src/method/eTrack/index.js',
        output: {
            filename: 'eTrack.js',
            path: path.resolve(__dirname, 'dist'),
            library: 'eTrack',
            libraryTarget: 'umd'
        },
    };
    

    ./src/method/eTrack/index.js:

    import create from './create';
    import getAll from './getAll';
    import getByName from './getByName';
    import remove from './remove';
    
    export function eTrack () {
    
    }
    eTrack.trackers = [];
    eTrack.create = create;
    eTrack.getAll = getAll;
    eTrack.getByName = getByName;
    eTrack.remove = remove;
    

    Well, after bundled via webpack, I can access eTrack in window but it turn out to be an object.That means I can't call eTrack() directly, but should call like eTrack.eTrack().

    And I've tried @Ambroos's solution, change ./src/method/eTrack/index.js into:

    module.exports = function eTrack () {
    
    }
    

    This time after bundled, I can't access eTrack in browser window, the eTrack object gone and it throws eTrack is undefined error in the console.

    Then I found an article that helps a lot:http://siawyoung.com/coding/javascript/exporting-es6-modules-as-single-scripts-with-webpack.html

    And change my index.js into:

    function eTrack () {
    
    }
    module.exports = eTrack;
    

    Then everything works as expected!I can call eTrack() directly in <script> tag.Though I don't know the difference between @Ambroos's answer and this solution.