簡體   English   中英

反應導入根路徑助手

[英]React import root path helper

在反應中因為我必須導入不同的助手或組件我有這個問題

import approxPerDay from '../../../utils/approxPerDay.js'
import otherstuff from '../components/otherstuff'

在另一個文件中,它可能是import approxPerDay from '../utils/approxPerDay.js'

找到相對路徑真的很難而且很耗時。 有沒有npm或者幫手可以解決這個問題?

我遇到了類似的問題。 我終於按照這篇文章解決了這個問題: https : //medium.com/@ktruong008/absolute-imports-with-create-react-app-4338fbca7e3d

  1. 在 react 應用程序的根目錄中創建一個 .env 文件
  2. 添加一行NODE_PATH = src/

那對我有用。

這取決於您的模塊捆綁器。 對於Webpack 2您可以執行以下操作:

module.exports = {
    ...

    resolve: {
        modules: [
            'node_modules',
            path.resolve(__dirname + '/src')
        ],
        alias: {
            src: path.resolve(__dirname + '/src')
        }
    },

    ...
}

Webpack 1相同:

module.exports = {
    ...

    resolve: {
        root: [
            path.resolve(__dirname  + '/src')
        ],
        alias: {
            src: path.resolve(__dirname  + '/src')
        }
    },

    ...
}

然后你就可以像這樣使用src作為本機路徑:

import approxPerDay from 'src/utils/approxPerDay.js'
import otherstuff from '../components/otherstuff'

您要問的是“絕對導入”。 “create react app”已經提供了標准方案,建議在你的react項目根目錄下創建一個jsconfig.json文件。

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

稍后您可以這樣導入組件:

import Button from 'components/Button';

Go 到這個與導入組件相關的官方文檔鏈接,你會在那里找到絕對導入部分:

https://create-react-app.dev/docs/importing-a-component/

是的,不要忘記在進行更改后重新啟動您的反應服務器:)

如果您需要指定 .env 文件和相對路徑,IDE 需要知道它。 為此,以下幾行適用於我的 IDE。

文件jsconfig.json

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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM