【问题标题】:how to use absolute paths instead of relative paths in React or Next.js?如何在 React 或 Next.js 中使用绝对路径而不是相对路径?
【发布时间】:2021-10-20 20:15:08
【问题描述】:

我正在使用 React,并且我在多个高阶组件中使用了多个组件,我的导入有时会像这样 import MyComponent from '../../../../components/MyComponent' 我知道通过更改包内的某些内容可以更有效地导入它.json 文件,然后像这样import MyComponent from '@components/myComponent' 导入它,但我不记得我该怎么做,我该怎么做?

【问题讨论】:

标签: javascript node.js reactjs npm


【解决方案1】:

如果您使用的是 TypeScript,您可以使用 jsconfigtsconfig 来执行此操作。

  1. 将 jsconfig.json 文件添加到项目的根目录。
  2. 在您的 jsconfig.json 文件中添加以下代码。
  3. 使用命令 npm start 启动您的 react 应用。

jsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

如果您使用 Next.js,这可能会有所帮助 https://nextjs.org/docs/advanced-features/module-path-aliases

【讨论】:

  • 非常感谢,我正在使用 Next.js 您包含的链接回答了我的问题。我正在使用打字稿,所以更改 tsconfig.json 文件为我做了。
【解决方案2】:

在根目录下创建一个 jsconfig.json 并复制下面的代码。重新启动 VSCode 以应用更改 -

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

【讨论】:

    【解决方案3】:

    在 next.js 中,这对我有用=>

    在根文件夹中,创建 jsconfig.json(如果使用 typescript,则为 tsconfig.json)文件。然后添加这个

     { 
       "compilerOptions": { "baseUrl": "." },
       "include":["."]
     }
    

    在根文件中创建一个“组件”文件夹,然后它会是这样的:

    // components/button.js
    
    export default function Button() {
      return <button>Click me</button>
    }
    
    
    // pages/index.js
    
    import Button from 'components/button'
    
     export default function HomePage() {
        return (
         <>
          <h1>Hello World</h1>
          <Button />
         </>
       )
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 2016-11-14
      • 1970-01-01
      • 1970-01-01
      • 2015-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多