ES6 import from root

I’m currently playing around with React Native. I’m trying to structure my app, however it’s starting to get messy with imports.

--app/
    -- /components
        -- Loading.js
    -- index.ios.js

Now, within my index.ios.js i’m able to simply do:

  • How to make Mocha display correct line numbers in source files if a test fails?
  • How to use data returned by an asynchronous function in Node.js?
  • Write After End error in node.js webserver
  • Node.js: Connecting to a Server Using Sockets
  • How to set _id to db document in Mongoose?
  • How do you call a function with parameters in a .then function in a JavaScript promise string?
  • import Loading from './components/Loading';

    However, when I start to create more components, with a deeper directory struture, it starts to get messy:

    import Loading from '.../../../../components/Loading';

    I understand the preferred solution would be to make private npm modules for things, but that’s overkill for a small project.

    You could do a global.requireRoot type solution on the browser, but how do I implement this with import?

  • Expressjs bodyParser and connect-form
  • ember js association access backend nodejs mongoose
  • How to add custom nodes and properties to AlloyUI diagram builder
  • Npm install cannot find module 'semver'
  • Is there any limit to setTimeout?
  • Converting enums to array of values (Putting all JSON values in an array)
  • 2 Solutions collect form web for “ES6 import from root”

    Had the same issue with React.
    So i wrote some plugin for babel which make it possible to import the modules from the root perspective – the paths are not shorter – but it’s clear what you import.

    So instead of:

    import 'foo' from '../../../components/foo.js';
    

    You can use:

    import 'foo' from '~/components/foo.js';
    

    Here is the Plugin (tested and with a clear README)

    If you are using Webpack you can configure it via the resolve property to resolve a your import path.

    Webpack 1

    resolve: {
      root: [
        path.resolve(__dirname  + '/src')
      ]
    }......
    

    Webpack 2

    resolve: {
      modules: [
        path.resolve(__dirname + '/src'),
        path.resolve(__dirname + '/node_modules')
      ]
    }.....
    

    After that you can use

    import configureStore from "store/configureStore";
    

    instead of the:

    import configureStore from "../../store/configureStore";
    

    Webpack will configure your import path from the passed resolve param.

    The same stuff you can do with System.js loader but with it’s own config param (it’s can be map or path. Check it in the System.js documentation) (if you would like to use it. It’s mostly for a Angular 2 case. But I suggest: don’t use standard System.js even if you are working with ng2. Webpack is much better).

    Node.js is the Best Javascript runtime in the world.