Search code examples
dynamicimporttypeerrornuxt3.js

dynamic import in Nuxt3 results in TypeError: Failed to resolve module specifier - but works when path is passed directly


This works:

<script setup lang="ts">
const data = await import('~~/myPath/myFile')
console.log(data)
</script>

But this does not work:

<script setup lang="ts">
const path = '~~/myPath/myFile'
const data = await import(path)
console.log(data)
</script>

It results in the error TypeError: Failed to resolve module specifier '~~/myPath/myFile'

The server engine is Nitro 1.0.0, Nuet version is 3.0.0


Solution

  • Here's the reason: Rollup security for file loading

    I got it to work like this:

    <script setup lang="ts">
    const data = await import('../../../myPath/myFile.ts')
    console.log(data)
    </script>
    

    And template literals work as well, such as

    const pathName = "myPath"
    const fileName = "myFile"
    import(`../../../${pathName}/${fileName}.ts`)
    

    The number of ../ depend on the file structure. It's relative to the path of the file, that is calling the myFile.ts