Best way to have absolute imports with Webpack 2?

风格不统一 提交于 2021-02-09 07:05:21

问题


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:

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

    
        resolve: {
          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


回答1:


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



来源:https://stackoverflow.com/questions/45384356/best-way-to-have-absolute-imports-with-webpack-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!