Giter Club home page Giter Club logo

babel-plugin-root-import's Introduction

Babel plugin to add the opportunity to use import and require with root based paths.
Build Status Dependency Status https://github.com/entwicklerstube/babel-plugin-root-import Codacy Badge

Example

// Without this plugin...
import SomeExample from '../../../some/example.js';
const OtherExample = require('../../../other/example.js');
import('../../../other/dynamic').then((mod) => {
  // ...
});

// With babel-plugin-root-import you can write...
import SomeExample from '~/some/example.js';
const OtherExample = require('~/other/example.js');
import('~/other/dynamic').then((mod) => {
  // ...
});

Install

Install with your package manager of choice.

npm install babel-plugin-root-import --save-dev

or

yarn add babel-plugin-root-import --dev

Use

Add it to your plugins array in your babel config, e.g. a .babelrc file.

{
  "plugins": [
    ["babel-plugin-root-import"]
  ]
}

For recent react-native versions, add it as a plugin in babel.config.js:

module.exports = (api) => {
  api.cache(true);

  return {
    plugins: ['babel-plugin-root-import'],
  };
};

For the rest of this readme, it's implied that you'll configure the plugin as above when using react-native.

Config

You can configure this plugin by changing the string plugin name to a two-item array. Note that this array is nested inside the plugins array. Here's an example with the default config.

  "plugins": [
    [
      "babel-plugin-root-import",
      {
        "rootPathSuffix": "./",
        "rootPathPrefix": "~/"
      }
    ]
  ],

Multiple rules may be specified by creating an object with { "paths": [firstItem, secondItem] }, e.g.

  "plugins": [
    [
      "babel-plugin-root-import",
      {
        "paths": [
          {
            "rootPathSuffix": "./src/components",
            "rootPathPrefix": "~/"
          },
          {
            "rootPathSuffix": "./src/utils",
            "rootPathPrefix": "!/"
          },
        ]
      }
    ]
  ],

Custom rootPathSuffix

By default, the import will be relative to the working directory of the process running babel. Typically this means you'll have import paths like ~/src/foo.js. You can change the prefix of "./" to e.g. "src" or "src/js" with this config option.

{
  "plugins": [
    ["babel-plugin-root-import", {
      "rootPathSuffix": "src/js"
    }]
  ]
}

The paths "src/js" and "./src/js" behave the same.

Custom rootPathPrefix

If you don't like the ~ syntax you can use your own symbol (for example an # symbol or \ or anything you want). Using @ is not recommended as NPM allows @ in package names. ~ is the default since it's very unlikely to conflict with anything (and wouldn't be expanded to HOME anyway).

{
  "plugins": [
    ["babel-plugin-root-import", {
      "rootPathPrefix": "#/"
    }]
  ]
}

// Now you can use the plugin like this
import foo from '#/my-file';

If you set it to e.g. "#/" then it'll require the slash in the import path.

Custom root

By default everything is resolved relative to the current working directory. You can change this with the root config option. To use it effectively, you'll need to configure babel with one of the JavaScript config file variants, rather than JSON.

For example, the following .babelrc.js file causes imports to resolve relative to the directory .babelrc.js is in.

const rootImportOpts = {
  root: __dirname,
  rootPathPrefix: '~/',
  rootPathSuffix: 'src/js',
};

module.exports = {
  plugins: [['babel-plugin-root-import', rootImportOpts]],
};

babel.config.js

const rootImportOpts = {
  root: __dirname,
  rootPathPrefix: '~/',
  rootPathSuffix: 'src/js',
};

module.exports = (api) => {
  api.cache(true);

  const plugins = [['babel-plugin-root-import', rootImportOpts]];

  return { plugins };
};

Function root variant

This .babelrc.js aliases @/foo to ./internals/foo.js since it's always relative to the file doing the import (contrived example).

const rootImportOpts = {
  root: (sourcePath) => path.dirname(sourcePath),
  rootPathPrefix: '@/',
  rootPathSuffix: 'internals',
};

module.exports = {
  plugins: [['babel-plugin-root-import', rootImportOpts]],
};

Transform paths for custom functions

If you have the need to transform paths also for other function calls you can configure them. But please be aware that this is kind of error prone because custom function names in Javascript are not static and can differ.

{
  "plugins": [
    ["babel-plugin-root-import", {
      "functions": ["jest.mock"]
    }]
  ]
}

// Now you can use the plugin also for jest.mock calls:
jest.mock('~/myfile')

Don't let ESLint be confused

If you use eslint-plugin-import to validate imports it may be necessary to instruct ESLint to parse root imports. You can use eslint-import-resolver-babel-plugin-root-import

  "settings": {
    "import/resolver": {
      "babel-plugin-root-import": {}
    }
  }

You may also specify a prefix/suffix if it doesn't correctly find your babel config.

  "settings": {
    "import/resolver": {
      "babel-plugin-root-import": {
        "rootPathPrefix": "~",
        "rootPathSuffix": "src"
      }
    }
  }

Don't let Flow be confused

If you use Facebook's Flow for type-checking it is necessary to instruct it on how to map your chosen prefix to the root directory. Add the following to your .flowconfig file, replacing {rootPathPrefix} with your chosen prefix (minus a trailing slash if any) and {rootPathSuffix} with your chosen suffix.

[options]
module.name_mapper='^{rootPathPrefix}/\(.*\)$' -> '<PROJECT_ROOT>/{rootPathSuffix}/\1'

Don't let VSCode be confused

For features like go-to-definition, VSCode needs to be able to resolve require/import paths to files on disk. This only works with one rootPathSuffix, but you may define multiple rootPathPrefix entries.

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

For example, with ~/x/y.js -> ./src/x/y.js:

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

FYI

Webpack delivers a similar feature, if you just want to prevent end-less import strings you can also define aliases in the resolve module, at the moment it doesn't support custom/different symbols and multiple/custom suffixes. READ MORE

Want to revert back to relative paths?

Sometimes tooling might not be up to scratch, meaning you lose features such as navigation in your IDE. In such cases you might want to revert back to using relative paths again. If you have a significant amount of files, it might be worth looking into tooling to help you with the conversion.

Change Log

6.6.0 - 2020-10-23

  • support template literals in dynamic import/require

6.4.1 - 2019-07-18

  • fixes unicode paths on windows

6.4.0 - 2019-07-18

  • add support for require.resolve
  • add support to configure additional require-like functions

6.3.0 - 2019-07-17

Adds 'root' config option.

6.2.0 - 2019-05-09

  • Remove the 2 characters restriction

6.1.0 - 2018-06-23

  • Supports babel 7

5.0.0 - 2017-02-10

  • More consistent name: babel-plugin-root-import #63
  • Renamed everything
  • Publish with new name on npm

4.1.5 - 2016-11-17

  • Compile new version and release again

4.1.4 - 2016-11-15

  • Improve support for relative paths (e.g. referencing parent folders via ../) (thanks to @Hizoul)

4.1.3 - 2016-09-14

  • Support paths (thanks to @sivael)

4.1.0 - 2016-08-20

  • Use relative paths instead of absolute ones (thanks to @nescalante)

4.0.0 - 2016-06-29

3.2.2 - 2016-02-20

  • Fix custom suffix in path, missing / in generated paths

3.2.0 - 2016-02-19

  • Support Windows-Filesystem
  • Add possibility to configure a custom rootPath-Symbol (instead of ~ you can use whatever you like)

3.1.0 - 2015-12-01

  • Add possibility config the custom root path

3.0.1 - 2015-11-30

  • Updated plugin to new babel6 API
  • Splitted tests and functions into two scopes with single tests
  • Removed the "extra-root" param for the .babelrc since this is no yet supported in babel6

2.0.1 - 2015-11-15

Breaking Change to Babel 5

  • Updated to Babel 6
  • Added integration tests

1.0.1 - 2015-08-07

  • Added / updated tests
  • Implemented ESlint

babel-plugin-root-import's People

Contributors

baptiste-garcin avatar brigand avatar codacy-badger avatar damonmaria avatar degr avatar designorant avatar dougmbarcellos avatar fatso83 avatar fredericheem avatar gpfunk avatar graingert avatar hizoul avatar idpaterson avatar mairu avatar mastilver avatar michaelbitard avatar michaelzoidl avatar nescalante avatar niekert avatar olalonde avatar sbauch avatar sheepsteak avatar timcabbage avatar vihanb avatar vincentcharpentier avatar yinanfang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

babel-plugin-root-import's Issues

Override root path

Hi!

Is there any way to override the root path? Basically, I have folder "src" and want to import directly from this folder.

Example:

// this works
import Test from '~/src/components/Test';

// want this
import Test from '~/components/Test';

fail on windows

version 1.x was working fine for me
After a migration to babel@6 and update of this package

It's just because it's returning / instead of ''
PR is on its way ;)

Full path names?

Hey,

I have a little issue with this package. When compiling with babel-cli the output packages get a full file path name.

When using:
import "/Services/MyService";

it produces:
require("f:\\Coding\\Projects\\Website/source/Services/MyService");
And instead it should produce this.
require("/Services/MyService");

package is not updated in npm

Hey, I just realized it 20 days after the merge, but you never did npm run compile before doing the publish to npm so the code is not updated there.
Can you please do npm run compile and then re-publish a new patch?

Thanks in advance.

Doesn't work with create-react-app

Hello,

Would love to use this. My .../.../.../.../app dependency links look awful. However, I can't seem to get it working with create-react-app without ejecting. I've tried both adding .babelerc and editing package.json to no avail.

Has anyone had success with that? I'd like to postpone "ejecting" until very last moment but also would like to work in a nice environment.

configuration

Hello, I can't understand, how I can configure this plugin. Just for now, I found only one way - create new npm plugin with this index.js file:

global.rootPath = process.cwd() + (global.srcRootPath ? '/' + global.srcRootPath.replace(/^(/)|(/)$/g, '') : '');
module.exports = require('../babel-root-import/build/index.js');

in this case, I can set global.srcRootPath variable in my gulpfile.js. Please, modify your code with this lines, or please say, how I can do this customization. Many thanks.

Support for multichar string as rootPathPrefix

Great plugin. Would it be possible to enhance the rootPathPrefix option to accept multichar strings instead of only one character?

Example:

    plugins: [
        ['babel-root-import', [{
            'rootPathPrefix': 'CORE_PATH',
            'rootPathSuffix': 'core/app'
        }, {
            'rootPathPrefix': 'THEME_PATH',
            'rootPathSuffix': 'theme/app'
        }]]
    ]

Imports could look like this, which would be more readable to programmers that didn't write the code:
import config from 'THEME_PATH/config/config.app';

Won't work on .less or .scss?

It works fine with .js file but I got error of

Can't resolve './@/variables.less'

This won't support .less or .scss?

Parse paths aside from imports like `jest.unmock('~/some/file')`

When using jest tests, I often get a case like this:

jest.unmock('../../../classes/feed.js');
import Feed from '~/classes/feed';

I can use the nice project-relative path in the import statements, but not in the unmock paths.
I think this is not specifically related to a jest usecase, but rather a general issue.

Is it possible to include some functionality that allows the use of '~/...' in such cases? Maybe something like jest.unmock(pathToRoot('~/classes/feed.js'))?

Not working on electron app when packaged using electron-packager

Everything is working just fine on dev, but when I package app using electon-packager, imports are no longer working when I run packaged app.

Uncaught Error: Cannot find module '../../../../../../../../../../../../src/component/App'

It looks like it is trying to go up the directory tree from release version of app to the project root.

Dev folder structure is: projectRoot/src/component/App.jsx
Released package is inside project: projectRoot/release/appName/appName/Contents/Resources/app/src/component/App.jsx

React Native?

It looks like doesn't work with React Native. Am I right? Or I'm missing something.

Flow support

Hi,

Great plugin, really handy.

I'm having some issues getting flow to play nice though with the specified name_mapper regex.

Here's my .flowconfig

[ignore]
.*/node_modules

[include]

[libs]

[options]
module.name_mapper='^~\/\(.*\)$' -> '<PROJECT_ROOT>/\1'

And here is a file that flow is checking:

import * as types from '~/actions/actionTypes.js';

This is the flow error:

import * as types from '~/actions/actionTypes.js';
                            ^^^^^^^^^^^^^^^^^^^^^^^^^^ ~/actions/actionTypes.js. Required module not found

Support require

Currently it seems like only import is supported, it'd be nice to have both.

Registry returned 404

hi there,

I am getting a strange error in my project. After starting the npm dev server its trying to install the plugin. However it's searching for "babel-plugin-babel-root-import", which, of course, doesn't exist.

This is the log

Installing babel-plugin-babel-root-import...
npm info it worked if it ends with ok
npm verb cli [ '/usr/local/bin/node',
npm verb cli   '/usr/local/bin/npm',
npm verb cli   'install',
npm verb cli   'babel-plugin-babel-root-import' ]
npm info using [email protected]
npm info using [email protected]
npm verb request uri https://registry.npmjs.org/babel-plugin-babel-root-import
npm verb request no auth needed
npm info attempt registry request try #1 at 14:23:45
npm verb request id 7e6f343b96f6bb6b
npm http request GET https://registry.npmjs.org/babel-plugin-babel-root-import
npm http 404 https://registry.npmjs.org/babel-plugin-babel-root-import
npm verb headers { 'content-type': 'application/json',
npm verb headers   'cache-control': 'max-age=0',
npm verb headers   'content-length': '2',
npm verb headers   'accept-ranges': 'bytes',
npm verb headers   date: 'Mon, 30 May 2016 12:23:49 GMT',
npm verb headers   via: '1.1 varnish',
npm verb headers   age: '0',
npm verb headers   connection: 'keep-alive',
npm verb headers   'x-served-by': 'cache-ams4126-AMS',
npm verb headers   'x-cache': 'MISS',
npm verb headers   'x-cache-hits': '0',
npm verb headers   'x-timer': 'S1464611029.006618,VS0,VE98',
npm verb headers   vary: 'Accept-Encoding' }
npm verb stack Error: Registry returned 404 for GET on https://registry.npmjs.org/babel-plugin-babel-root-import
npm verb stack     at makeError (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:264:12)
npm verb stack     at CachingRegistryClient.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:242:14)
npm verb stack     at Request._callback (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:172:14)
npm verb stack     at Request.self.callback (/usr/local/lib/node_modules/npm/node_modules/request/request.js:200:22)
npm verb stack     at emitTwo (events.js:100:13)
npm verb stack     at Request.emit (events.js:185:7)
npm verb stack     at Request.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/request/request.js:1067:10)
npm verb stack     at emitOne (events.js:95:20)
npm verb stack     at Request.emit (events.js:182:7)
npm verb stack     at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/request/request.js:988:12)
npm verb statusCode 404
npm verb pkgid babel-plugin-babel-root-import
npm verb cwd /Users/mmintel/Projekte/prismic-react
npm ERR! Darwin 15.3.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "babel-plugin-babel-root-import"
npm ERR! node v5.11.1
npm ERR! npm  v3.9.3
npm ERR! code E404

npm ERR! 404 Registry returned 404 for GET on https://registry.npmjs.org/babel-plugin-babel-root-import
npm ERR! 404
npm ERR! 404  'babel-plugin-babel-root-import' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
npm verb exit [ 1, true ]

I used this project over here as a starter for my own https://github.com/stephmilovic/prismic-react and had this error from the beginning.. however the author is not answering my issue so I am trying my luck over here.

Thats my .babelrc:

{
  "presets": ["react", "es2015"],
  "env": {
    "development": {
      "presets": ["react-hmre"]
    }
  },
  "plugins": [
    "babel-root-import"
  ]
}

and that's the part of my webpack config:

{
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /(node_modules|bower_components)/
      }

Do you have any idea?

Thanks!

eslint mark import as invalid

The package is working but could you provide a way to get around flow and ESLint error? They keep saying that the import is invalid

image

src doesn't work as suffix

Just wanted to log this officially, as it's pretty confusing and hopefully prevents people from running into;/

rootPathSuffix does not work anymore

Hi,

current version 3.2.0 breaks on OSX and Ubuntu.

"browserify": {
    "transform": [
      "babelify"
    ]
  },
  "babel": {
    "presets": [
      "es2015",
      "react"
    ],
    "plugins": [
      "transform-runtime",
      [
        "babel-root-import",
        {
          "rootPathSuffix": "src"
        }
      ],
      "jsx-control-statements"
    ]
  }

Error:

Error: Cannot find module '/home/XXX/.gvm/pkgsets/go1.6rc1/global/src/bitbucket.org/XXX/XXX/clientsrc/web/apps/XXX/app/controllers/connection'

As you can see, the part "clientsrc" is the problem. I'm not sure which version worked, because I did not update for a while, but there is definitely something going on here.

Everything worked fine before, just updated and boom.

EDIT: Just confirmed, 3.1.0 works fine. It's 3.2.0 for sure, which causes the problem.

[QUESTION] Get working with require()?

Great plugin! So far this is my favorite solution to the ../../../../../../ require problem 😄

I had a question, would it be theoretically possible to also get this behavior with a CommonJS require import in addition to an import?

Would be nice to have this work in all situations if possible.

Usage with dynamic import()

Currently, this plugin does not work with dynamic imports, like this:

export default async function showHeavyUi() {
  const ExpensiveUi = await import('~/components/expensive-ui');

  return ExpensiveUi;
}

Is there a way to make this work?

I'd love to help create this feature, but I've never touched anything inside a babel plugin. I'd love to help test, document or whatever though!

root path ?

babel-root-import works fine when used with babel-node or with mocha.
Most projects have the source in src and the compiled Javascript in build,
Is there a way to set the root path to src ?
Otherwise, it doesn't work when the import is in the form of:
import blabla from "~/src/blabla";
because the file ~/src/blabla is in es6 whereas it should use ~/build/blabla

SyntaxError: Unexpected token export

configure:

plugins: [
["babel-plugin-root-import", {
"rootPathPrefix": "~",
"rootPathSuffix": "../src"
}]
]

code:

base.js

'use strict';

import Base from '~/common/controller/';

export default class extends Base {
  // async getAction() {
  //   let ret;

  //   ret = await super.getAction();
  //   this.success(ret);
  // }
}

controller/index.js

'use strict';


/**
 *  Base Restful controller
 */

export default class extends think.controller.rest {

error message:

[2017-02-14 11:11:28] [Error] /Users/luncher/work/admin-plus/src/common/controller/index.js:8
export default class extends think.controller.rest {
^^^^^^
SyntaxError: Unexpected token export

Babelify - rootPathSuffix giving error

Hi there,

I'm using Browserify with Babelify and setting the plugin there. It seems to be working great but as soon as I add rootPathSuffix I get this error...

{ [Error: Plugin 1 specified in "base" provided an invalid property of "rootPathSuffix" while parsing file: '[filename_omitted]']
  filename: '[filename_omitted]',

This is my Browserify Gulp task...

browserify({
    entries: [options.src], // Only need initial file, browserify finds the rest
    transform: [
        ['babelify', {
            ignore: /(libs)|(node_modules)|(plugins)/,
            compact: true,
            presets: ['es2015', 'react'],
            plugins: ['babel-root-import', {
                'rootPathSuffix': 'js/src'
            }]
        }],
        ['envify', {
            'global': true,
            '_': 'purge',
            NODE_ENV: 'production'}
        ]
    ], // We want to convert JSX to normal javascript
    debug: options.development, // Gives us sourcemapping
    cache: {},
    packageCache: {},
    fullPaths: options.development // Requirement of watchify
});

I also tried adding the settings to a .babelrc file but it did nothing. I feel like I'm making a rookie mistake here! :) Hopefully you can shed some light.

Many thanks

Using Babelify 7.3.0

IDE support

Hello, anybody have experience with IDE support? Currently using IJ Idea, and it can't resolve paths. Of course, I need to know how to do it with IJ Idea, but absolutely sure that it will be useful, if somebody share his experience with eclipse or netbeans.

Doesn't work with npm link?

I'm getting a weird error after npm linking a dependency:

[1] [piping] error given was: ReferenceError: Unknown plugin "babel-root-import" specified in "base" at 0, attempted to resolve relative to "/Users/olalonde/code/blockai/filepunk-widget/lib"
[1]     at /Users/olalonde/code/blockai/blockai-ui/node_modules/babel-core/lib/transformation/file/options/option-manager.js:204:17
[1]     at Array.map (native)
[1]     at Function.normalisePlugins (/Users/olalonde/code/blockai/blockai-ui/node_modules/babel-core/lib/transformation/file/options/option-manager.js:180:20)
[1]     at OptionManager.mergeOptions (/Users/olalonde/code/blockai/blockai-ui/node_modules/babel-core/lib/transformation/file/options/option-manager.js:300

imports fail when using babel-root-import

standard import statements for 3rd party dependency packages fail when using the babel-root-import package.

// Works without babel-root-import
// Fails when babel-root-import is configured to change rootPathSuffix.
import name from "package-name";

It appears to me that babel-root-import only works when importing your own local modules.

[FIXED] Problems with "rootPathSuffix"

Hi,
i am trying to use this wonderful plugin, but are having problems with defining root folder. I get this error message when i add it: provided an invalid property of "rootPathSuffix"

And this is how my .babelrc file looks like

{
"presets": ["react", "es2015", "stage-2"],
"plugins": ["babel-plugin-root-import", {"rootPathSuffix": "src"}]
}

did i do something wrong here ?

prefix/suffix are unintuitive names

Suffix implies something coming after, not something being replaced.

Ideas:

rootPathFind
rootPathReplace

rootPathPrefixFind
rootPathPrefixReplace

More consistent name: babel-plugin-root-import

Hi! Thanks for awesome plugin!

Babel's docs say about Plugin/Preset Shorthands. Most of plugins works well with that shorthand notation, but babel-root-import do not, because of its name.

Why this plugin wasn't named in common convention? Don't you think it would be better to rename the plugin?

For example, we've got this issue brunch/brunch#1549 in Brunch. Of course, issue will be fixed by our efforts, but wouldn't it be easier for users not to write babel-root-import, but just root-import, every time they want to use your plugin?

stopped working with react-native 0.43.3

I'm calling it like so: import { SplashContainer, FooterTabsContainer, SettingsContainer } from '~/containers' it should be reading from directory /Users/jasan/Desktop/ReactModoro/app/containers
It seems to add app/containers/Navigator in the path before

my babel rc file:

{  "presets": [
    "react-native-stage-0"
    ],
  "plugins": [
    ["babel-root-import", {
    "rootPathSuffix": "app"
    }]
  ]}

screenshot_2017_04_16_20_18_22

Relative Path on Windows

Hi guys,

Great job with relative paths , but I have problem on my windows developer machine. After update to version 4.1.1, I am not able to use this plugin. Relative paths are not correctly generated.

I assume problem is in helper.js line 36, where you controll first char to "/", whether sourcePath is absolute or not. Which I think is correct on unix machines, but on windows in variable sourcePath I have "C:" ...

If you could fix this problem, I would really appreciate it :-)

4.1.0 on NPM doesn't seem to be the right version

I'm trying to upgrade to 4.1.0 to get the relative import functionality but the version published to NPM doesn't seem correct. If you download the tarball, you'll see that the build folder is out of date. Can you try republishing?

README example missing brackets

The README is missing an array and therefore fails if you run as-is. Both the rootPathSuffix and rootPathPrefix need to be updated. Should look like this:

"plugins": [["babel-root-import", {
"rootPathSuffix": "src/js"
}]]

Thanks!
Marten

Searching for contributor

Hi guys, as you know and see i'm not that active for this repo, so i decided to add members to share the access rights for people who are motivated to work on new features and improve the plugin.

You guys have already worked on the code-base of this module, if you're interested to have access - just let me know, and i will add you.
@sheepsteak @Hizoul @mastilver

Thanks, Michael

Converting from 3.2.2 to 5.0.0

I'm trying to convert this resolver to use the updated version of babel-plugin-root-import. Inside the source code for that project, it uses the transformRelativeToRootPath helper function from babel-plugin-root-import.

Unfortunately, it seems the behaviour has changed significantly. The old behaviour does not match the new behaviour; Please see below.

Reproduction

I'm running this:

const transformedSource = transformRelativeToRootPath(source, rootPathSuffix, rootPathPrefix)

Old behaviour 3.2.2:

INPUT
-----
source: "@/file"
rootPathPrefix: "@"
rootPathSuffix: "/test/somepath"

OUTPUT
------
transformedSource: "/Users/adrianli/dev/eslint-import-resolver-babel-root-import/test/somepath/file"

New behaviour 5.0.0

INPUT
-----
source: "@/file"
rootPathPrefix: "@"
rootPathSuffix: "/test/somepath"

OUTPUT
------
transformedSource: "../../../../test/somepath/file"

Question

What do I have to do with the inputs to get the desired (old) behaviour? Or is there another way I can get this to point to the correct file?

Support re-export syntax

This plugin doesn't seem to handle export * from '@/somemodule' syntax. I believe we would need to duplicate this code to support ExportNamedDeclaration and ExportAllDeclaration.

Can I add multiple path to babelrc?

I have a very nested project and was hoping to establish multiple paths based on prefixes. For example:

@ equates to src/common
~ equates to src/views

So imports like below

import A from '@/main';     (gets the file from src/common/)
import B from '~/second';   (gets the file from src/views/)

tries to install a non-existent package called babel-plugin-babel-root-import via npm

If I have in .babelrc:
"plugins": [ "babel-root-import" ]
it tries to install 'babel-plugin-babel-root-import'. See the attached log and the following terminal output:

`> NODE_ENV=development node server.js

Installing babel-plugin-babel-root-import...
npm ERR! Darwin 15.5.0
npm ERR! argv "/Users/nch/.nvm/versions/node/v6.1.0/bin/node" "/Users/nch/.nvm/versions/node/v6.1.0/bin/npm" "install" "babel-plugin-babel-root-import"
npm ERR! node v6.1.0
npm ERR! npm v3.9.1
npm ERR! code E404
`
If I take out the plugins and don't use '~/' anywhere it's fine. Also it still runs ok even with the errors.
npm-debug.log.zip

Support for Visual Studio Code?

I've added the babel-root-import to my project but now the intellisence of Visual Studio Code is no longer resolving the imports correctly.
Any idea/experience in fixing this?

System.import cannot use root import

Hi, this code here System.import('~/containers/page') fails given this .babelrc

{
  "plugins": [
    "transform-react-jsx",
    "transform-strict-mode",
    "system-import-transformer",
    [
        "babel-root-import",
        {"rootPathSuffix": "client"}
    ]
  ],
  "presets": ["react", "es2015", "stage-2"] ,
  "env": {
      "development": {
        "presets": ["react-hmre"]
      }
  },
  ignore: ["/node_modules/"]
}

webpack reports this

Module not found: Error: Cannot resolve module '~/containers/page' in /home/user/project/client

however the old way, System.import('./containers/page') works just fine

Improve support of eslint-plugin-import

Hi there!

First of all, I would like to say thank you for your amazing work!

I came across to your project from this tweet, and while I was reading the docs, there was something that grab my attention, and is basically that you suggest to disable eslint-plugin-import... So at that moment I thought "it must be some other way to deal with this", and I guess there is one:

If you have some time, don't you mind to have a look to it? I was thinking that maybe we could provide a custom resolver, so it would be just a matter to include it from babel-root-import/eslint-plugin-import-resolver, what do you think?

Thanks!

Breaks in Babel 6

After upgrading to babel 6 this plugin throws an error.

TypeError: r.Transformer is not a function
    at new n (/MyProject/node_modules/babel-root-import/lib/babel-root-import.js:1:519)
    at i (/MyProject/node_modules/babel-root-import/lib/babel-root-import.js:1:1074)
    at Function.memoisePluginContainer (/MyProject/node_modules/babel-core/lib/transformation/file/options/option-manager.js:129:13)
    at Function.normalisePlugin (/MyProject/node_modules/babel-core/lib/transformation/file/options/option-manager.js:163:32)
    at /MyProject/node_modules/babel-core/lib/transformation/file/options/option-manager.js:199:30
    at Array.map (native)
    at Function.normalisePlugins (/MyProject/node_modules/babel-core/lib/transformation/file/options/option-manager.js:175:20)
    at OptionManager.mergeOptions (/MyProject/node_modules/babel-core/lib/transformation/file/options/option-manager.js:273:36)
    at OptionManager.addConfig (/MyProject/node_modules/babel-core/lib/transformation/file/options/option-manager.js:223:10)
    at OptionManager.findConfigs (/MyProject/node_modules/babel-core/lib/transformation/file/options/option-manager.js:366:16)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.