【问题标题】:Typescript module path resolution not working for .js filesTypescript 模块路径解析不适用于 .js 文件
【发布时间】: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


    【解决方案1】:

    我通过在 webpack 中为 Typescript 文件使用两个加载器来修复它。

    {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
            'thread-loader',
            { loader: 'babel-loader'}
        ],
    },
    {
        test: /\.ts(x?)$/,
        exclude: /node_modules/,
        use: [
            {
                loader: 'thread-loader',
            },
            {
                loader: 'babel-loader',
            },
            {
                loader: 'ts-loader',
                options: {
                    happyPackMode: true,
                }
            },
        ],
    },
    

    【讨论】:

      猜你喜欢
      • 2019-12-12
      • 1970-01-01
      • 2021-11-10
      • 2022-01-15
      • 2016-10-03
      • 2023-04-07
      • 2017-07-01
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多