[英]React Typescript - Webpack externals module can not find
I created a react application using create-react-app with typescript template and run the eject command too.我使用带有打字稿模板的 create-react-app 创建了一个反应应用程序,并运行了弹出命令。
I just need to get configuration from external json file and read it from components file, anywhere in the application.我只需要从外部 json 文件中获取配置并从应用程序中任何位置的组件文件中读取它。 So I did following change to use webpack config json
所以我做了以下更改以使用 webpack config json
tsconfig.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 // Load external configuration files webpack.configjson // 加载外部配置文件
externals: {
'Configurator': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
}
Ts file ts文件
import Configurator from 'Configurator';
But it gives following error但它给出了以下错误
You need to change this line and make sure your config.*.js files are exporting modules:您需要更改这一行并确保您的 config.*.js 文件正在导出模块:
externals: {
'Configurator': JSON.stringify(process.env.NODE_ENV) === 'production' ? path.resolve(__dirname, 'config.prod.js') : path.resolve(__dirname, 'config.dev.js')
}
Try adding the following to your tsconfig.json尝试将以下内容添加到您的 tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
...
},
...
}
You can also try to use a non-relative path for your import since this will reduce the complexity of your webpack and tsconfig, then you can drop the webpack external config and do something like.您也可以尝试使用非相对路径进行导入,因为这会降低 webpack 和 tsconfig 的复杂性,然后您可以删除 webpack 外部配置并执行类似的操作。
in webpack.config在webpack.config
...
plugins: [new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})],
...
Then import like so:然后像这样导入:
const config = process.env.NODE_ENV === 'production' ? require('../config.prod.js') : require('../config.dev.js')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.