node.jsnpmimportmodulenpm-request

nodejs convert from import to require


I'm getting into a case not covered in How to bulk convert some javascript code from import to require?.

Here is the original code from npm package hot-import:

import * as assert  from 'assert'
import * as fs      from 'fs'
import * as path    from 'path'

import hotImport  from 'hot-import'

I converted them to,

const assert = require('assert')
const fs = require('fs')
const path = require('path')

const hotImport = require('hot-import')
const hotMod = await hotImport(MODULE_FILE)

but got:

TypeError: hotImport is not a function

After some massive trial-and-errors, I found that const { hotImport } = require('hot-import') works, but I have no idea why.

Can somebody summarize, when to use const hotImport = require('hot-import') and when to use const { hotImport } = require('hot-import') please?

And also related, why the demo code use,

import * as fs      from 'fs'

instead of

import fs      from 'fs'

? what's the differences between the two, and when to choose which?


Solution

  • Suppose in fs package there are 5 exports available in fs package as following

    export const readFile = _readFile;
    export const appendFile = _appendFile;
    export const writeFile = _writeFile;
    export const open = _open;
    export default fs; // fs class
    

    Now,

    1.

    import * as fs from 'fs'
    

    is asking to import all the named export from 'fs' in a local variable named fs. First 4 in above snippets are named exports. so now you can use them as fs.open('/home/demo.txt') or fs.writeFile('/home/demo.txt',...)

    2.

    import { open } from 'fs'
    

    is asking to import name export 'open' from fs into a local variable named open. so now you can use it as open('/home/demo.txt')

    3.

    import fs from 'fs'
    

    is asking to import the default export of the 'fs' module in the local fs variable that is the fs class in our example.

    So when you are doing const hotImport = require('hot-import') then it is importing the default export from 'hot-import'. So you cannot directly use it as hotImport(MODULE_FILE), instead you can use hotImport.hotImport(MODULE_FILE).

    You can read more about destructuring.

    const person = {
      first: 'Ridham',
      last: 'Tarpara',
      country: 'India',
      city: 'Ahmedabad',
      twitter: '@ridhamtarpara'
    };
    

    If you have person object then following two code will be the same

    const first = person.first; // Ridham
    const last = person.last;   // Tarpara
    
    const { first, last } = person; // first = Ridham, last = Tarpara