使用 Webpack 2 进行绝对导入的最佳方式? [英] Best way to have absolute imports with Webpack 2?
问题描述
我正在为 React 项目设置 Webpack 配置,我希望能够像这样导入我的组件:
从components/ComponentName"导入ComponentName
而不是这样:
从../../components/ComponentName"导入ComponentName
(这一切都假设我的 components
目录位于 src
目录中)
做了一点研究,到目前为止,我发现了两种不同的方法来使用 Webpack 实现这一点:
使用
<前><代码>解决: {模块:[ path.resolve(__dirname, "src"), path.resolve(__dirname, "node_modules")]}resolve.modules
选项使 Webpack 解析我的src
目录中的模块,如下所示:使用别名选项将我的组件目录命名为别名:
<前><代码>解决: {别名:{组件:path.resolve(__dirname, 'src/components/'),}}
那么,我的问题是,使用一种特定方法比另一种方法有什么优势吗?
提前致谢
当你使用别名时,你可以像这样导入你的代码
解析:{别名:{别名:path.resolve(__dirname, 'src/components/'),}}从 'AliasName/Comp' 导入 Comp
当您不使用别名时,您的代码将如下所示
解析:{模块:[ path.resolve(__dirname, "src"), path.resolve(__dirname,节点模块")]}从'components/Comp'导入Comp
我会使用别名,因为它看起来更干净,但它没有真正的优势.只是外观和感觉
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:
Making Webpack resolve modules inside my
src
directory using theresolve.modules
option like this:resolve: { modules: [ path.resolve(__dirname, "src"), path.resolve(__dirname, "node_modules")] }
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
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
这篇关于使用 Webpack 2 进行绝对导入的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!