简体   繁体   中英

Best way to have absolute imports with Webpack 2?

I'm in the process of setting up a Webpack configuration for a React project and I want to be able to import my components like this:

import ComponentName from "components/ComponentName"

instead of like this:

import ComponentName from "../../components/ComponentName"

(this all would be assuming that my components directory lives inside a src directory)

Doing a little bit of research, so far I've found two different methods to achieve this using Webpack:

  1. Making Webpack resolve modules inside my src directory using the resolve.modules option like this:

    \nresolve: { modules: [ path.resolve(__dirname, "src"), path.resolve(__dirname, "node_modules")] }\nresolve: { modules: [ path.resolve(__dirname, "src"), path.resolve(__dirname, "node_modules")] } 
  2. Using the Alias option to name my components directory as an alias:

    \nresolve: { alias: { components: path.resolve(__dirname, 'src/components/'), } }\nresolve: { alias: { components: path.resolve(__dirname, 'src/components/'), } } 

So, my question is, is there any advantage of using one particular method over the other ?

Thanks in advance

When you use alias you can import your code like this

resolve: {
  alias: {
    AliasName: path.resolve(__dirname, 'src/components/'),
   }
}

import Comp from 'AliasName/Comp'

Where as when you dont use alias your code would look like this

resolve: {
  modules: [ path.resolve(__dirname, "src"), path.resolve(__dirname, 
  "node_modules")]
}

import Comp from 'components/Comp'

I would go with the alias cause it looks a lot cleaner but there is no real advantage to it. Just the look and feel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM