在Node.js上使用dynamic import()函数

hmae6n7t  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(205)

我正在尝试在Node v10环境中实现dynamic import的基本功能。

main.js

async function main() {
  try {
    const moduleA = await import('./moduleA');
    console.log('Inside main function...');
    moduleA();
    console.log(moduleA);
  }
  catch(err) {
    console.log(err);
  }
}

main();

moduleA.js

console.log('Inside global scope module A...');

function moduleA() {
  console.log('Running module A function...');
}

export default moduleA;

这是我运行npx babel-node main.js时得到的结果

PS C:\myProject\test-module-imports> npx babel-node src/main.js
Inside global scope module A...
Inside main function...
TypeError: moduleA is not a function
    at main (C:\myProject\test-module-imports\src/main.js:9:5)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
    at Object.<anonymous> (C:\myProject\test-module-imports\node_modules\@babel\node\lib\_babel-node.js:174:21)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)

**.babelrc

{
  "presets": [
    [
      "@babel/preset-env", {
        "targets": {
          "node": "10"
        }
      }
    ]
  ]
}

我也试过这个(下面的代码)。结果是一样的:

main.js

let moduleA = null;
import('./moduleA').then((importedModule) => {
  moduleA = importedModule;
  main();
});

async function main() {
  try {
    // const moduleA = await import('./moduleA');
    console.log('Inside main function...');
    moduleA();
    console.log(moduleA);
  }
  catch(err) {
    console.log(err);
  }
}

// main();

问题

我做错了什么?
这是正常工作(常规导入):使用npx babel-node src/main.js执行

import moduleA from './moduleA';

async function main() {
  try {
    console.log('Inside main function...');
    moduleA();
    console.log(moduleA);
  }
  catch(err) {
    console.log(err);
  }
}

main();

package.json(额外信息)

{
  "name": "test-module-imports",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.7.0",
    "@babel/core": "^7.7.2",
    "@babel/node": "^7.7.0",
    "@babel/preset-env": "^7.7.1"
  }
}
yhived7q

yhived7q1#

dynamic import()加载模块并返回一个包含其所有导出的模块对象。要访问默认导出,请使用模块对象的default属性:

const moduleA = await import('./moduleA');
moduleA.default();

// OR

const { default: moduleA } = await import('./moduleA');
moduleA();

相关问题