webpack 里动态引用文件 require.context 类型报错问题

webpack 里一个好用的特性,可以动态引入文件
更新于: 2023-11-01 16:17:00

背景

require.context 报错问题

安装

npm i -D @types/webpack-env

配置

tsconfig.json 关键配置:"webpack-env"

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "types": [
      "node",
      "webpack-env"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "noImplicitAny": false,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

以前

以前只能用上万能的 // @ts-ignore 来解燃眉之急了。

// @ts-ignore
const ctx = require.context("./src/modals/", true, /\.(ts|js|tsx|jsx)$/);

参考