How to avoid using relative path imports (/../../.

2020-05-15 09:56发布

I've been using create-react-app package for creating a react website. I was using relative paths throughout my app for importing components, resources, redux etc. eg, import action from '../../../redux/action

I have tried using module-alis npm package but with no success. Is there any plugin that I can use to import based on the folder name or alias i.e. an absolute path?

Eg., import action from '@redux/action' or import action from '@resource/css/style.css'

7条回答
何必那么认真
2楼-- · 2020-05-15 10:37

You can use absolute imports as described in another answers with baseUrl in tsconfig.json or jsconfig.json (instead of obsolete NODE_PATH).

However if you want to have alias for any directories (included dirs outside os src) as you declared in question:

import action from '@redux/action'
import style from '@resource/css/style.css'

It require modify webpack config which is possible with eject or better with rewire.

Use alias solution. It provide more then just alias but it allows also multiple src folders in root directory:

Configure for your above example like this:

// config-overrides.js:

const {alias} = require('react-app-rewire-alias')

module.exports = function override(config) {
  alias({
    "@redux": "src/redux",
    "@resource": "resource", // or "src/resource" if it is in src
  })(config)
  return config
}

or load paths from jsconfig.json or tsconfig.json with configPaths()

查看更多
登录 后发表回答