sunchao
sunchao

Reputation: 1

Compiled with errors when a Vue3 application uses dynamic imports to load components based on a variable path

I am working with a Vue 3 project using TypeScript and SCSS. When I dynamically import components using require, Webpack fails to compile, throwing errors related to SCSS files being loaded multiple times and issues with shims-vue.d.ts. The errors disappear when I remove the following code:

router_obj.component = require(`@/${item.component}`).default;

I attempted to replace require with require.context to dynamically load components, but I encountered a new error from vue-router: TypeError: Cannot use 'in' operator to search for 'catch' in undefined. Below is the code I used:

component: () => {
  // Use require.context to import components
  const requireComponent = require.context('@/', true, /\.vue$/);

  // Filter out undefined item.menu_component
  if (item.menu_component !== undefined) {
    router_obj.component = requireComponent(
      `./${item.menu_component}`
    ).default;
  }
},

my project environment:

node: 18.20.4

npm: 10.7.0

package.json:

"dependencies": {
    "@element-plus/icons-vue": "^2.1.0",
    "axios": "^1.3.4",
    "dayjs": "^1.11.10",
    "element-plus": "^2.3.4",
    "vue": "^3.2.13",
    "vue-router": "^4.0.3",
    "vuex": "^4.0.0"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^5.4.0",
    "@typescript-eslint/parser": "^5.4.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-plugin-router": "~5.0.0",
    "@vue/cli-plugin-typescript": "~5.0.0",
    "@vue/cli-plugin-vuex": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "@vue/eslint-config-typescript": "^9.1.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "sass": "^1.65.1",
    "sass-loader": "^13.3.2",
    "svg-sprite-loader": "^6.0.11",
    "typescript": "~4.5.5"
  }

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "useDefineForClassFields": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

Upvotes: 0

Views: 29

Answers (0)

Related Questions