Search code examples
javascripttypescriptwebpackwebpack-2

webpack - how do these import statements differ?


Assuming the use of webpack 2, and typescript, what exactly is the difference between these statements.

import "moment";
import "imports-loader?window=>this!moment";
import "script-loader!moment";
import * as moment from "moment";
import { moment } from "moment";

In the case of webpack 2 what happens exactly...
Despite trawling through the (IMHO bad) documentation, it's not very clear to me.

I have found, for example, that using the script-loader seems to make some libraries available to other libraries imported with the script-loader but does not put it into global scope for other ES6 imported libraries.

for reference: my tsconfig.json looks like this:

{
  "compileOnSave": true,
  "compilerOptions": {
    "moduleResolution": "node",
    "target": "es5",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "pretty": true,
    "lib": [ "es6", "dom" ],
    "types": []
  },
  "exclude": [
    "node_modules", "wwwroot/lib", "bower_components"
  ]
}

Solution

  • The three forms:

    import "moment";
    import * as moment from "moment";
    import { moment } from "moment";
    
    • import "moment";

    Imports a file for side effects.

    • import * as moment from "moment";

    Imports a full module into the file as named moment

    • import { moment } from "moment";

    Imports the named export moment from the module moment.

    More

    Read up on ES6 imports / module syntax 🌹

    Webpack

    Webpack also allows you to use loaders in import e.g.

    import "imports-loader?window=>this!moment";
    import "script-loader!moment";
    

    These are covered in individual loader docs e.g. https://github.com/webpack-contrib/imports-loader