【发布时间】:2019-05-05 04:21:29
【问题描述】:
我有一个 React 项目,我想开始将 js 文件迁移到 typescript。如果我在另一个 .tsx 文件中导入 .tsx 设置的别名有效,但如果我尝试在 .tsx 文件中导入 .js 文件则不起作用。
// inside app.tsx
import Main from 'Components/main'; // works if main is a .tsx file but not .js
我收到此错误
找不到模块:错误:无法解析“组件/主”
如果我使用 ./components/main.js 可以,但我想使用别名。
webpack.config.js
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
alias: {
Components: path.resolve(__dirname, '/app/components/'),
},
},
rules: [
{
test: /\.ts|.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'thread-loader',
{ loader: 'babel-loader'}
],
},
},
//... other loaders
]
...
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"removeComments": true,
"baseUrl": ".",
"sourceMap": true,
"paths": {
"App": ["app"],
"Components/*": ["app/components/*"],
}
},
"include": [
"./app/"
],
"exclude": [
"./node_modules/"
]}
如果我可以在 js 文件中使用 typescript 路径别名,那就太好了。我在 tsconfig.json 中将 allowJS 设置为 true 但还是不行。
【问题讨论】:
标签: reactjs typescript webpack alias