在 React 应用程序中使用 babel 模块解析器 + eslint + 索引文件时无法解析模块

Unable to resolve module when using babel module resolver + eslint + index files in react application

我正在尝试将 babel module resolver plugin 与 eslint + create react app 一起使用,但我无法启动该应用程序,出现错误

internal/modules/cjs/loader.js:1237
throw err;
^

SyntaxError: C:\Users\enisr\Desktop\projects\pcPartPicker\jsconfig.json: 
Unexpected token } in JSON at position 166
at parse (<anonymous>)

我已经建立了一个 git 回购协议来展示这个问题 https://github.com/sgoulas/pcPartPicker

我已阅读说明in the docs and in the original repository,但无法正确配置。

我的配置文件如下:

.babelrc

{
"plugins": [
    ["module-resolver", {
        "extensions": [
            ".js",
            ".jsx",
            ".es",
            ".es6",
            ".mjs"
        ],
            "root": ["./src"],
            "alias": {
                "@components": "./src/components"
            }
        }
    ]
]
}

jsconfig.json

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

webpack.config.dev.js

var path = require("path");

module.exports = {
  include: path.appSrc,
  loader: require.resolve("babel-loader"),
  options: {
    plugins: [
     [
    "module-resolver",
    {
      root: ["./src/App"],
      alias: {
        "@components": "./src/components",
      },
        },
      ],
    ],
    cacheDirectory: true,
  },
};

我的组件:

import { GPUtable, CPUtable } from "@components/Tables";

const App = () => {
  return (
    <>
      <GPUtable />
      <CPUtable />
    </>
  );
};

导出默认应用;

您需要进行一些小修复(如下),但主要问题是 Create React App 不会公开 webpack 配置,您需要 eject 进行编辑。

  1. npm run eject
  2. 合并 babel 配置:删除 package.json 底部的 babel 键 + 值,并将该值粘贴到您的 bablrc ("presets": ["react-app"],) 中。
  3. import React from 'react'; 添加到 App.js
  4. 的顶部

在本地确认该应用程序将 运行。


其他建议的修复

  1. 您的 jsconfig 在 @components/* 中的数组值之后有一个尾随逗号。您需要删除它,因为 JSON 不会 support them.
  2. 您需要修复 weback.config.dev.js 中的 include 路径。 appSrc 不是在节点 path 模块上定义的东西。尝试使用 path.resolve(__dirname, 'src') - 他们文档中的示例是 creating/importing 一个 paths 对象 appSrc 指向这个值。
  3. 您在 webpack.config.dev.js 中缺少 test: /\.(js|jsx|mjs)$/,