Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

javascript - Relative Imports in React.js

Currently I have an import which looks like this

import Button from "../../../components/Button/Button"

but I want to make it relative so I wouldn't require to type the ../../../ time and again.

I want to import using this method:

import Button from "components/Button/Button" or src/components/Button/Button

but please also assure that it will work on both production and development.

question from:https://stackoverflow.com/questions/65713724/relative-imports-in-react-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are using webpack. You can use resolve.

const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
      Utilities: path.resolve(__dirname, 'src/utilities/'),
      Templates: path.resolve(__dirname, 'src/templates/'),
      Components: path.resolve(__dirname, 'src/components/'),
    }
  }
};

Now, instead of using relative paths when importing like so:

import Utility from '../../utilities/utility';
import Button from '../../src/components/Button';

you can use the alias:

import Utility from 'Utilities/utility';
import Button from 'Components/Button';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...