1.ts中如何使用webpack的require.context
参考:https://github.com/DefinitelyTyped/DefinitelyTyped/issues/6170#issuecomment-331650124
步骤:
- 1.安装
@types/webpack-env
- 2.配置tsconfig.json
{
"compilerOptions": {
...
"types": [
"node",
"webpack-env"
]
},
...
}
动态引入模块的ts代码
import React from 'react';
interface Context {
[x: string]: any;
};
const context: Context = {};
const req = require.context('.', true, /Store$/);
req.keys().forEach(key => {
const keyMatches = key.match(/(a-zA-Z0-9.*)$/);
if (keyMatches && keyMatches[1]) {
const name = keyMatches[1];
const Store = req(key).default;
context[name] = new Store();
}
});
export const storesContext = React.createContext(context);
上面的做法已经过时
新的解决方法
参考:require.context()语法在ts环境下的配置:https://zhuanlan.zhihu.com/p/88325577
下载两个包来解决这个问题
npm i @types/webpack-env @types/node -D