Nodejs 从 import 转换为 require

xpt*_*xpt 4 import module node.js npm npm-request

我遇到了如何将某些 javascript 代码从导入批量转换为 require?中未涵盖的情况。

\n\n

这是npm 包中的原始代码hot-import

\n\n
import * as assert \xc2\xa0from \'assert\'\nimport * as fs \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0from \'fs\'\nimport * as path \xc2\xa0\xc2\xa0\xc2\xa0from \'path\'\n\nimport hotImport \xc2\xa0from \'hot-import\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

我将它们转换为,

\n\n
const assert = require(\'assert\')\nconst fs = require(\'fs\')\nconst path = require(\'path\')\n\nconst hotImport = require(\'hot-import\')\nconst hotMod = await hotImport(MODULE_FILE)\n
Run Code Online (Sandbox Code Playgroud)\n\n

但得到:

\n\n
TypeError: hotImport is not a function\n
Run Code Online (Sandbox Code Playgroud)\n\n

经过一些大量的试验和错误后,我发现这是const { hotImport } = require(\'hot-import\')可行的,但我不知道为什么。

\n\n

有人可以总结一下什么时候使用const hotImport = require(\'hot-import\')以及什么时候使用const { hotImport } = require(\'hot-import\')吗?

\n\n

还有相关的,为什么演示代码使用,

\n\n
import * as fs \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0from \'fs\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

代替

\n\n
import fs \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0from \'fs\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

?两者之间有什么区别,何时选择哪个?

\n

Rid*_*ara 8

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
Run Code Online (Sandbox Code Playgroud)

Now,

1.

import * as fs from 'fs'
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)

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'
};
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)