reactjs - 如果我在 tsconfig 中使用自定义路径,Webpack 开发服务器找不到带有 Typescript 的模块
问题描述
我正在 React + TypeScript 上从头开始构建一个项目,并使用 Webpack Dev 服务器。我想使用组件的相对路径,这对于更灵活的开发来说并不严格。
在我的 App.tsx 中,我正在尝试导入组件:
import EntityTypes from "components/EntityTypes/EntityTypes";
并得到一个错误
Module not found: Error: Can't resolve 'components/EntityTypes/EntityTypes' in '/home/eugene/prj/work/crud-react/src'
此路径的文件存在(/src/components/EntityTypes/EntityTypes.js)并导出类
export default EntityTypes;
我的 tsconfig.json:
{
"compilerOptions": {
"sourceMap": true,
"noImplicitAny": false,
"module": "commonjs",
"target": "es5",
"lib": [
"es2015",
"es2017",
"dom"
],
"removeComments": true,
"allowSyntheticDefaultImports": false,
"jsx": "react",
"allowJs": true,
"baseUrl": ".",
"paths": {
"components/*": [
"src/components/*"
]
}
}
}
webpack.config.js:
const HtmlWebPackPlugin = require( 'html-webpack-plugin' );
const path = require( 'path' );
module.exports = {
context: __dirname,
entry: './src/index.js',
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},
output: {
path: path.resolve( __dirname, 'dist' ),
filename: 'main.js',
publicPath: '/',
},
devServer: {
historyApiFallback: true
},
module: {
rules: [
{
test: /\.(tsx|ts)?$/,
loader: 'awesome-typescript-loader'
},
{
test: /\.js$/,
use: 'babel-loader',
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|j?g|svg|gif)?$/,
use: 'file-loader'
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: path.resolve( __dirname, 'public/index.html' ),
filename: 'index.html'
})
]
};
我检查了关于“路径”的打字稿文档,该文件存在,我不明白是什么问题。
解决方案
我已经整理了如何为我的文件使用路径并使它们灵活,我可以轻松地重新组织项目和管理路径,而无需对严格的相对路径进行大量更改。
该问题与 webpack 的配置有关。接下来是最终配置:
tsconfig.json
{
"compilerOptions": {
// ...
"paths": {
"~/components/*": [
"./src/components/*"
],
"~/services/*": [
"./src/services/*"
],
"~/interfaces/*": [
"./src/interfaces/*"
]
},
}
}
webpack.config.js
const path = require('path');
module.exports = {
// ...
resolve: {
// ...
alias: {
'~/components': path.resolve(process.cwd(), './src/components'),
'~/interfaces': path.resolve(process.cwd(), './src/interfaces'),
'~/services': path.resolve(process.cwd(), './src/services'),
}
},
}
使用示例
import {IEntities} from "~/interfaces/entities.interface";
// ...
import EntityForm from "~/components/EntityForm/EntityForm";
推荐阅读
- ios - 如何开始使用 Video-To-Texture 渲染?
- bash - 无法在循环的 bash 脚本中触摸带有 var 名称的文件
- android - 如何从 YesHttp 发送 http 请求
- c# - 如何在一个视图中显示两个 ActionResult
- javascript - javascript的“更改”函数在asp.net mvc中不起作用
- node.js - 如何使用 websockets/ws lib 限制 Websocket 连接的数量?
- linux - 使用 perf 测量到达主要功能的时间?
- r - 在 R 中查找具有标头要求和 mutate() 挑战的行的最大值
- python - 如何将值保存到python中的列表
- azure - 使用 azure-blob 组件在 apache camel 中获取“无效的客户端 URI”