[英]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: 我正在为React项目设置Webpack配置,我希望能够像这样导入我的组件:
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) (这一切都假设我的
components
目录位于src
目录中)
Doing a little bit of research, so far I've found two different methods to achieve this using Webpack: 做了一点研究,到目前为止,我发现了两种使用Webpack实现此目的的方法:
Making Webpack resolve modules inside my src
directory using the resolve.modules
option like this: 使我里面的WebPack决心模块
src
使用目录resolve.modules
这样的选项:
\nresolve: { modules: [ path.resolve(__dirname, "src"), path.resolve(__dirname, "node_modules")] }
\nresolve: { modules: [ path.resolve(__dirname, "src"), path.resolve(__dirname, "node_modules")] }
Using the Alias option to name my components directory as an alias: 使用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
只是外观和感觉
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.