简体   繁体   English

TypeScript 编译器错误,同时找到 `tsconfig.json` 中提到的绝对路径

[英]TypeScript compiler error while finding absolute paths mentioned in `tsconfig.json`

I have the following directory structure:我有以下目录结构:

.
├── \ .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

And tsconfig.json looks like:并且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"
    ]
}

My App.tsx looks like:我的App.tsx看起来像:

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

TS error looks like: 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'

How do I solve this?我该如何解决这个问题? I'm following Next.js absolute imports structure .我正在关注Next.js 绝对导入结构

Even tried doing:甚至尝试做:

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

But it still gives error.但它仍然给出错误。 How do I solve it?我该如何解决?

I have webpack.config.js too, which looks like:我也有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

Do I have to specify anything in webpack.config.js ?我是否必须在webpack.config.js中指定任何内容? Because VSCode autocomplete is working just fine.因为 VSCode 自动完成工作得很好。

It was a webpack issue, not TS which I found through https://decembersoft.com/posts/say-goodbye-to-relative-paths-in-typescript-imports/这是一个 webpack 问题,而不是我通过https://decembersoft.com/posts/say-goodbye-to-relative-paths-in-typescript-imports/找到的 TS

I kept tsconfig.json as it is:我保持tsconfig.json原样:

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

And I had to add the following code to webpack.config.js :我必须将以下代码添加到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,
        },
    },
}

That did the trick那成功了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Typescript 编译器在 tsconfig.json 上包含文件时找不到绝对路径 - Typescript compiler not finding absolute paths when including files on tsconfig.json TypeScript编译器忽略tsconfig.json中的声明文件 - TypeScript compiler ignores declaration file in tsconfig.json tsconfig.json 路径在构建中未解析 - tsconfig.json paths are not resolved in build 为什么打字稿编译器会在服务器启动时更改我的 tsconfig.json 文件? - Why is typescript compiler changing my tsconfig.json file on server start up? TypeScript。 在 tsconfig.json 中使用 ESNext 作为目标时如何防止转译? - TypeScript. How prevent transpiling while using ESNext as a target in tsconfig.json? tsconfig.json 仅在某些时候尊重 baseUrl 绝对导入 - tsconfig.json honoring baseUrl absolute imports only some of the time tsconfig.json 的编译器选项它们从何而来? - tsconfig.json 's compiler options where do they come from? 将tsconfig.json放置在Symfony Encore中以定义TypeScript配置? - Where to place tsconfig.json in Symfony Encore to define TypeScript config? 为什么 Vite 会创建两个 TypeScript 配置文件:tsconfig.json 和 tsconfig.node.json? - Why does Vite create two TypeScript config files: tsconfig.json and tsconfig.node.json? 如何使用 tsconfig.json 修复此错误 - How do I fix this error with tsconfig.json
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM