Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

Babel aliases. WebStorm doesn't recognize sub-directories

I recently moved from webpack path aliases to babel-plugin-module-resolved as it integrates better with testing frameworks.

.babelrc

{
  "presets": [
    ["env", { "modules": false } ],
    "react",
    "stage-2",
    "flow"
  ],
  "plugins": [
    ["module-resolver", {
      "alias": {
        "static": "./static",
        "common": "./src/common",
        "data": "./src/data"
      }
    }],
    ["styled-jsx/babel", { "plugins": ["styled-jsx-plugin-sass"] }],
    "react-hot-loader/babel"
  ]
}

WebStorm automatically recognizes imports for static/.. but can't resolve imports like common/.. and data/...

Is it possible to somehow instruct IDE about this configuration?

P.S. Right now I have src directory marked as Resource Root but this doesn't quite work as well.

Upvotes: 2

Views: 1983

Answers (2)

Elder
Elder

Reputation: 41

Following SimplyComplexable's solution (I can't comment on his reply, sorry), I've create a new webpack.intellij.js that loads the project's webpack config (webpack.js), reads the .babelrc file to generates the resolve.alias section for the exported config, then explicitly pointed IntelliJ to this file in the preferences:

const path = require('path');
const fs = require('fs');
const { merge } = require('webpack-merge');

const webpackConfig = require('./webpack.js');

const babelRc = JSON.parse(fs.readFileSync('./.babelrc').toString('utf8'));

const aliases = {};
for (let i = 0; i < babelRc.plugins.length; i+=1) {
  if (Array.isArray(babelRc.plugins[i]) && 
      babelRc.plugins[i][0] === 'module-resolver') {
    const a = babelRc.plugins[i][1].alias;
    for (const entry of Object.entries(a)) {
      aliases[entry[0]] = path.resolve(__dirname, entry[1]);
    }
  }
}

module.exports = merge(webpackConfig, {
  resolve: {
    alias: aliases
  }
});

This solution allows me to have the aliases configured in one single place (.babelrc) while still having IntelliJ recognise them :)

Upvotes: 0

SimplyComplexable
SimplyComplexable

Reputation: 1114

One option I've taken is to create a fake webpack file that creates the same aliases. Leaves an unnecessary file in your codebase, but fixes all the name resolution issues.

Example: webpack.junk.js

module.exports = {
  resolve: {
    alias: {
      'static': path.resolve(__dirname, './static'),
      '@common': path.resolve(__dirname, './src/common'),
      '@data': path.resolve(__dirname, './src/data'),
    },
  },
};

Upvotes: 8

Related Questions