Webstorm ES6 命名导入出现"cannot resolve symbol"错误

18

在使用 ES6 命名导入声明时,我在 Webstorm 中遇到了一个错误:

import { nodes } from 'utils/dom';

我在 "nodes" 上遇到了 "cannot resolve symbol" 错误。

当我尝试像这样导出命名导出时:

export {
  write: document.write.bind(document),
  node: document.querySelector.bind(document),
  nodes: document.querySelectorAll.bind(document)
};

我也遇到了错误。 我使用babel-eslint解析器的eslint。 问题是在Sublime Text 3中可以完美运行,但由于某种原因,在Webstorm中无法进行错误检查。

我认为这是因为除了Eslint之外,webstorm还在进行其他代码检查。

有什么办法可以抑制它,并仅使用babel-eslint解析器的eslint吗?

任何建议都将不胜感激。


你的导出有问题,这不是导出的正确方式。不确定导入的情况。在这种情况下,“utils”是什么?这不是标准路径,因为它不是相对文件路径。你是否在某个地方有自定义模块解析逻辑? - loganfsmyth
你可以导出对象,然后在本地路径中导入 { property }。局部变量 property 将被分配为已导出属性的值。语法没有问题,它可以很好地工作。它不应该是相对文件路径。我使用 webpack 和 babel loader。我不需要相对文件路径,因为我使用 webpack 配置中的 moduleDirectories 在一组文件夹中进行搜索。所以归根结底就是它能够工作。而且这是正确的,问题是为什么 WebStorm 显示它是错误的。 - Vladimir Novick
@VladimirNovick 你是如何解决这个问题的呢? - smilingpoplar
2个回答

11

我在"nodes"上得到了"无法解析符号"的错误,是因为标准Node代码中的utils/dom表示"在名为'utils'的模块中查找dom.js"。您已经通过使用Webpack的moduleDirectories属性覆盖了此行为,但WebStorm不知道这是什么意思。为了让WebStorm正确解析utils/dom,您需要将utils文件夹添加为WebStorm项目配置中的库。

您的export语法不正确。ES6的import/export语法与对象完全无关,在您的示例导出中,您正在使用对象语法。 import { nodes }要求导入一个名为nodes的导出。您可以以多种方式编写您的导出:

export const write = document.write.bind(document);
export const node = document.querySelector.bind(document);
export const nodes = document.querySelectorAll.bind(document);

或者,如果您喜欢多行的var/let/const,您也可以将它们折叠起来。


export const write = document.write.bind(document),
    node = document.querySelector.bind(document),
    nodes = document.querySelectorAll.bind(document);

甚至更多

const write = document.write.bind(document);
const node = document.querySelector.bind(document);
const nodes = document.querySelectorAll.bind(document);


export {write, node, nodes};

5

很难说这是否直接相关,但为了使Webstorm知道如何解析您的导入内容,您还可以进入首选项>目录,并将文件夹设置为资源根目录(或右/上下文单击文件夹并以此方式设置)

例如,在您配置Webpack以解决特定子目录时,可能需要执行此操作,在此情况下您的项目结构可能是:

/
  /docs
  /src
    /containers
      /app
        App.js
    /components
      /header
        Header.js

在这种情况下,Webstorm 期望在 App.js 中进行导入的格式如下所示:
import Header from '../../../components/header/Header'

如果您已将src添加为要解析的模块,则可以使用Webpack执行以下操作,但是 Webstorm 目前无法理解,因此将其添加为资源根会解决该问题。

import Header from 'components/header/Header'

参考文献:Webstorm中导入的路径别名


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接