简体   繁体   English

WebStorm 中导入的路径别名

[英]Path aliases for imports in WebStorm

I use webpack path aliases for ES6 module loading.我使用 webpack 路径别名来加载 ES6 模块。

Eg If I define an alias for utils instead of something like例如,如果我为utils定义别名而不是类似的东西
import Foo from "../../../utils/foo" , I can do import Foo from "../../../utils/foo" ,我可以
import Foo from "utils/foo"

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 使用这样的别名?

Yes, there is.就在这里。

In fact, Webstorm can't automatically parse and apply Webpack config, but you can set up aliases the same way.实际上,Webstorm 并不能自动解析和应用 Webpack 配置,但您可以通过相同的方式设置别名。

You just have to mark the parent folder of "utils" (in your example) as a resource root (right-click, mark directory as / resource root).你只需要标注“utils的”(在你的例子),作为一个资源根(右击,标记目录/资源根)的文件夹。

右键单击文件夹

We just managed to do with the following structure :我们只是设法使用以下结构:

/src
    /A
    /B
    /C

We have AB and C folders declared as alias in Webpack.我们在 Webpack 中将 AB 和 C 文件夹声明为别名。 And in Webstorm we marked "src" as "Resource Root".在 Webstorm 中,我们将“src”标记为“Resource Root”。

And now we can simply import :现在我们可以简单地导入:

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

instead of代替

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

while still having Webstorm correctly parsing and indexing all code, link to files, autocompleting and so on ...同时仍然让 Webstorm 正确解析和索引所有代码,链接到文件,自动完成等等......

I managed to set up aliases for WebStorm 2017.2 within webpack like this:我设法在 webpack 中为 WebStorm 2017.2 设置别名,如下所示:

在此处输入图片说明

For the record: in PHPSTORM , working with laravel mix , I managed to solve this by creating a webpack.config.js file separately like:作为记录:在PHPSTORM 中,使用laravel mix ,我设法通过单独创建一个 webpack.config.js 文件来解决这个问题,例如:

const path = require('path')
const webpack = require('webpack')

module.exports = {
  ...
  resolve: {
    extensions: ['.js', '.json', '.vue'],
    alias: {
      '~': path.resolve(__dirname, './resources/assets/js')
    }
  },
  ...
}

And then importing it in the webpack.mix.js like:然后在 webpack.mix.js 中导入它,如:

const config = require('./webpack.config')
...
mix.webpackConfig(config)

Make sure the webpack configuration file is pointed correctly in the configuration of the PhpStorm in: Settings > Languages & Frameworks > Javascript > Webpack确保在 PhpStorm 的配置中正确指向 webpack 配置文件:设置 > 语言和框架 > Javascript > Webpack

You can define custom paths, so WebStorm/PhpStorm can understand your aliases.您可以定义自定义路径,以便 WebStorm/PhpStorm 可以理解您的别名。 But make sure, they are identical with your aliases.但请确保它们与您的别名相同。 Create file in your root directory and call it something like this: webStorm.config.js (any js file will be ok).在您的根目录中创建文件并命名为: webStorm.config.js (任何js文件都可以)。 Then configure your paths inside:然后在里面配置你的路径:

System.config({
  "paths": {
    "components/*": "./src/components/*",
    "core/*": "./src/core/*",
    ...
  }
});

WebStorm/PhpStorm will recognize System as it's own module and will treat this file as configuration. WebStorm/PhpStorm 会将System识别为它自己的模块,并将将此文件视为配置。

This is answered in a comment but to save people digging into comments and link only information, here it is:这是在评论中回答的,但为了避免人们深入研究评论并仅链接信息,这里是:

As of WS2017.2 this will be done automatically .从 WS2017.2 开始,这将自动完成 The information is here .信息在这里

According to this, webstorm will automatically resolve aliases that are included within the webpack.config in the root of the project.据此,webstorm 将自动解析项目根目录下webpack.config中包含的别名。 If you have a custom structure and your webpack.config isn't in the root folder then go to Settings | Languages & Frameworks | JavaScript | Webpack如果您有自定义结构并且您的webpack.config不在根文件夹中,请转到Settings | Languages & Frameworks | JavaScript | Webpack Settings | Languages & Frameworks | JavaScript | Webpack Settings | Languages & Frameworks | JavaScript | Webpack and set the option to the config you require. Settings | Languages & Frameworks | JavaScript | Webpack并将选项设置为您需要的配置。

Note: Most setups have a base config which then call a dev or prod version.注意:大多数设置都有一个base配置,然后调用devprod版本。 In order for this to work properly, you need to tell webstorm to use the dev one .为了使其正常工作,您需要告诉 webstorm 使用 dev one

Not right now , We were also using path aliases for the files in our react project.不是现在,我们还为我们的 React 项目中的文件使用了路径别名。 The import names were shorter but we lost a lot on static checking of webstorm as well as completion features.导入名称较短,但我们在 webstorm 的静态检查以及完成功能方面丢失了很多。

We later came up with a decision to reduce the code to only 3 levels of depth, as well a single level for the common parts.我们后来决定将代码减少到只有 3 个深度级别,以及公共部分的一个级别。 The path completion feature of webstom (ctrl + space) even helps reduce the typing overhead. webstom 的路径补全功能(ctrl + space)甚至有助于减少打字开销。 The production build does not use longer names, so hardly makes any difference in final code.生产版本不使用更长的名称,因此最终代码几乎没有任何区别。

I will suggest please reconsider your decision about aliases.我建议请重新考虑您对别名的决定。 You loose semantic meaning of modules coming from node_modules and your own code, as well as referencing the alias files again and again to make sense of your code, is a much bigger overhead.来自 node_modules 和您自己的代码的模块的语义松散,以及一次又一次地引用别名文件以理解您的代码,是一个更大的开销。

In PHPStorm (using 2017.2 currently), I have not been able to get webpack configs to work properly in regards to aliases.在 PHPStorm(目前使用 2017.2)中,我无法让 webpack 配置在别名方面正常工作。

My fix involves using the "Directories" section of the main settings.我的修复涉及使用主要设置的“目录”部分。 I just had to mark each folder referenced by an alias as a sources root, then click the properties dropdown for each and specify the alias as a "Package prefix".我只需要将别名引用的每个文件夹标记为源根目录,然后单击每个文件夹的属性下拉列表并将别名指定为“包前缀”。 This made everything link up for me.这让我的一切都联系起来了。

Not sure if the Directories section exists in WebStorm, but if it does, this seems to be a fool-proof method for getting import aliases working.不确定 WebStorm 中是否存在 Directories 部分,但如果存在,这似乎是使导入别名工作的万无一失的方法。

For anyone struggling: path.resolve() must be called with "__dirname" first argument for Idea (Websorm) to be able to resolve the path correctly.对于任何挣扎的人:path.resolve() 必须使用“__dirname”第一个参数调用 Idea (Websorm) 才能正确解析路径。

Will work for Idea (Websorm):将适用于 Idea (Websorm):

alias: {
    '@someAlias': pathLib.resolve(__dirname, 'path/to/directory')
}

Will not work for Idea (Websorm) (while still being valid webpack alias):不适用于 Idea (Websorm)(同时仍然是有效的 webpack 别名):

alias: {
    '@someAlias': pathLib.resolve('path/to/directory')
}

Webstorm can't read webpack.config if module.exports return a function.如果module.exports返回一个函数,Webstorm 将无法读取 webpack.config。 For example例如

module.exports = function (webpackEnv) {
  return {
    mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
    ...
 }
}

Check your config file, maybe this cause you are a problem.检查您的配置文件,也许这会导致您出现问题。

add jsconfig.js on your project root在您的项目根目录中添加jsconfig.js

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~/*": ["./src/*"]
    }
  }
}

Had the same problem on a new Laravel project with Jetstream.在使用 Jetstream 的新 Laravel 项目中遇到了同样的问题。 The webpack.config.js was present and correct. webpack.config.js存在且正确。 But PHPStorm still didn't recognize the @ symbol as a resource root.但是 PHPStorm 仍然没有将@符号识别为资源根。

After opening the webpack config, I got a notification:打开 webpack 配置后,我收到一条通知:

PHPStorm 通知

After Clicking on Trust project and run , the @ symbol became recognized.单击Trust 项目并运行后@符号被识别。

I know that this isn't the solution or use-case for everyone.我知道这不是适合所有人的解决方案或用例。 But I still found it worthy to note on this post, because it helped me in my situation.但我仍然发现这篇文章值得一提,因为它在我的情况下帮助了我。

Using使用

  • laravel/framework:8.77.1
  • npm:8.3.0
  • node:v14.18.1

There is a lot of discussion here about Laravel Mix, so I'll leave this here to help out future readers.这里有很多关于 Laravel Mix 的讨论,所以我将把它留在这里以帮助未来的读者。 I solved this by creating a separate (fake) webpack config file which is only used by my IDE (PHPStorm).我通过创建一个单独的(假的)webpack 配置文件来解决这个问题,该文件仅由我的 IDE (PHPStorm) 使用。

1. Create a separate alias.js file (eg /webpack/alias.js) 1.创建一个单独的alias.js文件(例如/webpack/alias.js)

const path = require('path');

const assets = path.join(__dirname,'..','resources','assets');

module.exports = {
    '@js'        : path.resolve(assets, 'js'),
    '@c'         : path.resolve(assets, 'js', 'components'),    
    '@errors'    : path.resolve(assets, 'js', 'errors'),
    '@utils'     : path.resolve(assets, 'js', 'utils'),
    '@store'     : path.resolve(assets, 'js', 'store'),
    '@api'       : path.resolve(assets, 'js', 'api'),
    '@less'      : path.resolve(assets, 'less')
}

2. Require the alias.js file into webpack.mix.js 2. 将alias.js文件引入webpack.mix.js

const mix  = require('laravel-mix');

mix.alias(require('./webpack/alias'))
   // ... The rest of your mix, e.g.
   .js('app.js')
   .vue()
   .less('app.less');

3. Create the fake webpack config for your IDE (eg /webpack/ide.config.js) 3. 为你的 IDE 创建伪造的 webpack 配置(例如 /webpack/ide.config.js)

Here, import the laravel-mix webpack config, plus your aliases, and any other config that the IDE might need help finding.在这里,导入 laravel-mix webpack 配置,加上您的别名,以及 IDE 可能需要帮助查找的任何其他配置。 Also include the prefixed ~ aliases for importing styles into your Vue components.还包括前缀 ~ 别名以将样式导入 Vue 组件。

/*
 |--------------------------------------------------------------------------
 | A fake config file for PhpStorm to enable aliases
 |--------------------------------------------------------------------------
 |
 |   File > Settings... > Languages & Frameworks > Javascript > Webpack
 |
 |   Select "Manually" and set the configuration file to this
 |
*/
const path = require('path');
const mixConfig = require('./../node_modules/laravel-mix/setup/webpack.config')();

module.exports = {
    ...mixConfig,
    resolve: {
        alias: {
            ...require('./alias'),
            '~@less' : path.resolve('@less'), // <-- 
        },
        ...mixConfig.resolve
    }
}

4. Set your IDE to use webpack/ide.config.js as your webpack config file. 4. 将您的 IDE 设置为使用webpack/ide.config.js作为您的 webpack 配置文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM