【问题标题】:TypeScript compiler error while finding absolute paths mentioned in `tsconfig.json`查找 `tsconfig.json` 中提到的绝对路径时出现 TypeScript 编译器错误
【发布时间】:2021-03-31 22:15:59
【问题描述】:

我的目录结构如下:

.
├── \ .babelrc
├── README.md
├── package-lock.json
├── package.json
├── postcss.config.js
├── public
│   ├── icon128.png
│   ├── icon16.png
│   ├── icon48.png
│   ├── manifest.json
│   └── popup.html
├── src
│   ├── App.tsx
│   ├── background.ts
│   ├── components
│   │   ├── Main.tsx
│   │   ├── Options.tsx
│   │   ├── SiteImage.tsx
│   │   ├── TrafficSignal.tsx
│   │   └── index.ts
│   ├── content.ts
│   ├── custom.d.ts
│   ├── popup.tsx
│   ├── store
│   │   ├── FrameItContext.tsx
│   │   ├── FrameItStore.ts
│   │   └── index.ts
│   ├── styles
│   │   ├── popup.css
│   │   └── tailwind.css
│   └── types
│       └── index.ts
├── tailwind.config.js
├── tsconfig.json
└── webpack.config.js

而tsconfig.json 看起来像:

{
    "compilerOptions": {
        "baseUrl": "node_modules",
        "paths": {
            "@/*": ["../src/*"]
        },
        "outDir": "./dist/",
        "sourceMap": true,
        "strict": true,
        "noImplicitReturns": true,
        "noImplicitAny": true,
        "module": "es6",
        "moduleResolution": "node",
        "target": "es5",
        "allowJs": true,
        "jsx": "react",
    },
    "exclude": ["node_modules"],
    "include": [
        "./src/**/*",
        "src/custom.d.ts"
    ]
}

我的App.tsx 看起来像:

import { Main } from '@/components/index'
import { config, FrameItProvider } from '@/store/index'

TS 错误如下:

ERROR in ./src/App.tsx 2:0-42
Module not found: Error: Can't resolve '@/components/index'

ERROR in ./src/App.tsx 3:0-48
Module not found: Error: Can't resolve '@/store/index'

我该如何解决这个问题?我正在关注Next.js absolute imports structure。

甚至尝试过:

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@/*": ["./src/*"]
        },
}

但它仍然给出错误。我该如何解决?

我也有webpack.config.js,看起来像:

const webpack = require('webpack')
const path = require('path')
const CopyPlugin = require('copy-webpack-plugin')

const config = {
  entry: {
    popup: path.join(__dirname, 'src/popup.tsx'),
    content: path.join(__dirname, 'src/content.ts'),
    background: path.join(__dirname, 'src/background.ts'),
  },
  output: { path: path.join(__dirname, 'dist'), filename: '[name].js' },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader', 'postcss-loader'],
        exclude: /\.module\.css$/,
      },
      {
        test: /\.ts(x)?$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true,
            },
          },
        ],
        include: /\.module\.css$/,
      },
      {
        test: /\.svg$/,
        use: 'file-loader',
      },
      {
        test: /\.png$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              mimetype: 'image/png',
            },
          },
        ],
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.jsx', '.tsx', '.ts'],
    alias: {
      'react-dom': '@hot-loader/react-dom',
    },
  },
  devServer: {
    contentBase: './dist',
  },
  plugins: [
    new CopyPlugin({
      patterns: [{ from: 'public', to: '.' }],
    }),
  ],
}

module.exports = config

我必须在webpack.config.js 中指定任何内容吗?因为 VSCode 自动完成功能很好。

【问题讨论】:

  • 你试过 "@/*": ["src/*"] 吗?
  • @KevinZhang 我刚才将baseUrl 设置为. 和node_modules,但不起作用。我的意思是 VSCode 自动完成功能有效,但 Webpack 抛出错误,所以可能是 Webpack 问题?
  • 设置baseUrl为.,同时设置路径为{ "@/*": ["src/*"] }
  • @KevinZhang 我已经这样做了。我确实尝试了两种组合
  • @KevinZhang 问题出在 webpack 上。感谢decembersoft.com/posts/…,我解决了它,一旦我找到有效的方法,我会发布答案:)

标签: javascript typescript absolute-path tsconfig tsconfig-paths


【解决方案1】:

这是一个 webpack 问题,不是我通过 https://decembersoft.com/posts/say-goodbye-to-relative-paths-in-typescript-imports/ 找到的 TS

我保持tsconfig.json 原样:

{
    "compilerOptions": {
        "baseUrl": "node_modules",
        "paths": {
            "@/*": ["../src/*"],
        },
}

我必须将以下代码添加到webpack.config.js:

const fs = require('fs')

const srcPath = (subdir) => path.join(__dirname, 'src', subdir)
const getFilesAndDirectories = (source) =>
    fs.readdirSync(source, { withFileTypes: true }).map((dirent) => dirent.name)
let absoluteImports = {}
getFilesAndDirectories('src').forEach((fileName) => {
    const fileNameWithoutExtension = path.parse(fileName).name
    absoluteImports[`@/${fileNameWithoutExtension}`] = srcPath(fileName)
})

const config = {
    .
    .
    .
    resolve: {
        alias: {
            'react-dom': '@hot-loader/react-dom',
            ...absoluteImports,
        },
    },
}

成功了?

【讨论】:

    猜你喜欢
    • 2021-11-29
    • 2018-10-14
    • 2021-07-04
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多