WebStorm 中导入的路径别名 [英] Path aliases for imports in WebStorm

查看:61
本文介绍了WebStorm 中导入的路径别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 webpack 路径别名来加载 ES6 模块.

I use webpack path aliases for ES6 module loading.

例如如果我为utils定义一个别名而不是
从../../../utils/foo"导入Foo,我可以做到
从utils/foo"导入 Foo

E.g. If I define an alias for utils instead of something like
import Foo from "../../../utils/foo", I can do
import Foo from "utils/foo"

问题是,一旦我开始使用别名,WebStorm 就会失去对导入的跟踪,我会收到警告并且没有自动完成功能.

The problem is that once I start using aliases, WebStorm looses track of the import and I'm left with warnings and no auto-completion.

有没有办法让 WebStorm 使用这样的别名?

Is there a way to instruct WebStorm to use such aliases?

推荐答案

是的,有.

其实Webstorm并不能自动解析和应用Webpack config,但是你可以用同样的方法设置别名.

In fact, Webstorm can't automatically parse and apply Webpack config, but you can set up aliases the same way.

您只需标记utils"的文件夹即可.(在您的示例中)作为资源根目录(右键单击,将目录标记为/资源根目录).

You just have to mark the parent folder of "utils" (in your example) as a resource root (right-click, mark directory as / resource root).

我们只是设法使用以下结构:

We just managed to do with the following structure :

/src
    /A
    /B
    /C

我们在 Webpack 中将 A B 和 C 文件夹声明为别名.在 Webstorm 中,我们将src"标记为作为资源根".

We have A B and C folders declared as alias in Webpack. And in Webstorm we marked "src" as "Resource Root".

现在我们可以简单地导入:

And now we can simply import :

import A/path/to/any/file.js

代替

import ../../../../../A/path/to/any/file.js

同时仍然让 Webstorm 正确解析和索引所有代码、链接到文件、自动完成等......

while still having Webstorm correctly parsing and indexing all code, link to files, autocompleting and so on ...

这篇关于WebStorm 中导入的路径别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆