Search code examples
javascriptwebpackpapaparse

webpack difference between named and default import


So, in my webpack src, I tried

import {Papa} from "papaparse"
export {Papa}

and

import Papa from "papaparse"
export {Papa}

Notice on the second one, the import doesnt use curly braces. The one without curly braces (default import?) works when I call like this:

import {Papa} from "papaparse-webpack-generated.js"

Papa.parse(...)

and this is inside papaparse.js I downloaded using npm:

(function(root, factory)
{
    /* globals define */
    if (typeof define === 'function' && define.amd)
    {
        // AMD. Register as an anonymous module.
        define([], factory);
    }
    else if (typeof module === 'object' && typeof exports !== 'undefined')
    {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    }
    else
    {
        // Browser globals (root is window)
        root.Papa = factory();
    }
    // in strict mode we cannot access arguments.callee, so we need a named reference to
    // stringify the factory method for the blob worker
    // eslint-disable-next-line func-name
}(this, function moduleFactory()
{
    'use strict';
    var Papa = {};

    Papa.parse = CsvToJson;
    Papa.unparse = JsonToCsv;

    //a bunch of functions and variables here
    
    return Papa;
}));

I'm just wondering what's the difference between the two? why is the js generated by webpack would fail if I use curly braces? if I generated using webpack using the named import (curly braces), the Papa.parse would give me Papa is undefined

EDIT: we can see from the papaparse.js snippet above, there's no export statement for the variable Papa. Am I missing anything? So, how do we tell if it's named or default export?

Thanks


Solution

  • In the file you're importing from, you'll notice Papa is exported as "export default". A module can have a singular default export and any number of named exports.

    Default exports are imported with the syntax without the curly braces, and can have any name in the imported file (since the ambiguity isn't resolved by the name, but by the fact that the module can only have on default export).

    Named exports, on the other hand, have to be referenced by their specific name, and must be placed inside the curly braces, as to signal they're a named export. You can import multiple named exports, with the following syntax:

    import {NamedA, NamedB} from x
    

    Or even import both:

    import DefaultExport, {NamedA, NamedB} from x
    

    Read further here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import