1.ts中如何使用webpack的require.context
參考:https://github.com/DefinitelyTyped/DefinitelyTyped/issues/6170#issuecomment-331650124node
步驟:
- 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);
上面的作法已通過時react
新的解決方法
參考:require.context()語法在ts環境下的配置:https://zhuanlan.zhihu.com/p/88325577webpack
下載兩個包來解決這個問題git
npm i @types/webpack-env @types/node -D