![](/img/trans.png)
[英]Mocha + Webpack + Typescript (React): Error cannot find module (typescript component)
[英]React Typescript - Webpack externals module can not find
我使用带有打字稿模板的 create-react-app 创建了一个反应应用程序,并运行了弹出命令。
我只需要从外部 json 文件中获取配置并从应用程序中任何位置的组件文件中读取它。 所以我做了以下更改以使用 webpack config json
配置文件
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
webpack.configjson // 加载外部配置文件
externals: {
'Configurator': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
}
ts文件
import Configurator from 'Configurator';
但它给出了以下错误
您需要更改这一行并确保您的 config.*.js 文件正在导出模块:
externals: {
'Configurator': JSON.stringify(process.env.NODE_ENV) === 'production' ? path.resolve(__dirname, 'config.prod.js') : path.resolve(__dirname, 'config.dev.js')
}
尝试将以下内容添加到您的 tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
...
},
...
}
您也可以尝试使用非相对路径进行导入,因为这会降低 webpack 和 tsconfig 的复杂性,然后您可以删除 webpack 外部配置并执行类似的操作。
在webpack.config
...
plugins: [new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})],
...
然后像这样导入:
const config = process.env.NODE_ENV === 'production' ? require('../config.prod.js') : require('../config.dev.js')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.