Typescript模块路径解析不适用于.js文件

时间:2018-12-03 20:08:09

标签: reactjs typescript webpack alias

我有一个React项目,我想开始将js文件迁移到打字稿。如果我在另一个.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文件中使用打字稿路径别名,那就太好了。我在tsconfig.json中将allowJS设置为true,但还是不好。

1 个答案:

答案 0 :(得分:1)

我通过对webpack中的Typescript文件使用两个加载程序来修复它。

export default function Checkbox() {
  const isCheckedRef = useRef(false);
  const handler = () => {
    if (isCheckedRef.current)
      ...
  };

  useEffect(
    () => {
      window.addEventListener("beforeunload", handler);
      return () => {
        window.removeEventListener("beforeunload", handler);
      }
    },
    []
  );

  return (
    <input
      type="checkbox"
      checked={isCheckedRef.current}
      onChange={e => isCheckedRef.current = e.target.checked}
    />
  );
}