最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use await import() for an exported constructor function? - Stack Overflow

programmeradmin0浏览0评论

I have this as my function constructor:

test.js

const myConstructor = function(){
  this.hi = 'hi'
  console.log(this.hi)
}
export default myConstructor

And I'm trying to await import() it in test2.js:

test2.js

const test = await import('./test.js')

new test()

This fails with TypeError: test is not a constructor.

However, if I import it normally it works fine:

test2.js

import test from './test.js'
//const test = await import('./test.js')

new test()

^^ prints hi to the console.

What is going on here? Why do the two approaches behave so differently for constructor functions? This doesn't appear to happen for normal functions.

I've had to work around this by calling the constructor function directly within the constructor function module, and this is not ideal.

I have this as my function constructor:

test.js

const myConstructor = function(){
  this.hi = 'hi'
  console.log(this.hi)
}
export default myConstructor

And I'm trying to await import() it in test2.js:

test2.js

const test = await import('./test.js')

new test()

This fails with TypeError: test is not a constructor.

However, if I import it normally it works fine:

test2.js

import test from './test.js'
//const test = await import('./test.js')

new test()

^^ prints hi to the console.

What is going on here? Why do the two approaches behave so differently for constructor functions? This doesn't appear to happen for normal functions.

I've had to work around this by calling the constructor function directly within the constructor function module, and this is not ideal.

Share Improve this question asked Aug 23, 2022 at 21:59 DshizDshiz 3,3514 gold badges35 silver badges63 bronze badges 2
  • console.log(test) and show us what you got – Konrad Commented Aug 23, 2022 at 22:01
  • 1 console.log(test) gives me this for await import(): [Module: null prototype] { default: [Function: myConstructor] } and this for normal import: [Function: myConstructor] – Dshiz Commented Aug 23, 2022 at 22:03
Add a ment  | 

2 Answers 2

Reset to default 6

Dynamic import returns:

It returns a promise which fulfills to an object containing all exports from moduleName, with the same shape as a namespace import (import * as name from moduleName): an object with null prototype, and the default export available as a key named default.

If its Promise only resolved to the default export, you wouldn't be able to use any named exports it may have. So, you need:

const testNamespace = await import('./test.js')

new testNamespace.default()

Async import returns module, so you need to use .default property to access default export of module.

const test = await import('./test.js').default

new test()
发布评论

评论列表(0)

  1. 暂无评论