master d2640d517ecb
14 files
17.3 KB
5.0k tokens
Repository: mantrajs/babel-root-slash-import
Branch: master
Commit: d2640d517ecb
Files: 14
Total size: 17.3 KB

Directory structure:
gitextract_07hnpfxp/

├── .babelrc
├── .eslintrc
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── LICENSE
├── README.md
├── config/
│   └── mocha.js
├── index.js
├── package.json
├── plugin/
│   ├── helper.js
│   └── index.js
└── test/
    ├── helper.spec.js
    └── plugin.spec.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .babelrc
================================================
{
  "presets": ["es2015","stage-1"]
}


================================================
FILE: .eslintrc
================================================
{
  "parser": "babel-eslint",
  "env": {
    "browser": true,
    "node": true
  },
  "ecmaFeatures": {
    "arrowFunctions": true,
    "blockBindings": true,
    "classes": true,
    "defaultParams": true,
    "destructuring": true,
    "forOf": true,
    "generators": false,
    "modules": true,
    "objectLiteralComputedProperties": true,
    "objectLiteralDuplicateProperties": false,
    "objectLiteralShorthandMethods": true,
    "objectLiteralShorthandProperties": true,
    "spread": true,
    "superInFunctions": true,
    "templateStrings": true,
    "jsx": true
  },
  "rules": {
/**
 * Strict mode
 */
    // babel inserts "use strict"; for us
    // http://eslint.org/docs/rules/strict
    "strict": [2, "never"],

/**
 * ES6
 */
    "no-var": 2,                     // http://eslint.org/docs/rules/no-var
    "prefer-const": 2,               // http://eslint.org/docs/rules/prefer-const

/**
 * Variables
 */
    "no-shadow": 2,                  // http://eslint.org/docs/rules/no-shadow
    "no-shadow-restricted-names": 2, // http://eslint.org/docs/rules/no-shadow-restricted-names
    "no-unused-vars": [2, {          // http://eslint.org/docs/rules/no-unused-vars
      "vars": "local",
      "args": "after-used"
    }],
    "no-use-before-define": 2,       // http://eslint.org/docs/rules/no-use-before-define

/**
 * Possible errors
 */
    "comma-dangle": [2, "never"],    // http://eslint.org/docs/rules/comma-dangle
    "no-cond-assign": [2, "always"], // http://eslint.org/docs/rules/no-cond-assign
    "no-console": 1,                 // http://eslint.org/docs/rules/no-console
    "no-debugger": 1,                // http://eslint.org/docs/rules/no-debugger
    "no-alert": 1,                   // http://eslint.org/docs/rules/no-alert
    "no-constant-condition": 1,      // http://eslint.org/docs/rules/no-constant-condition
    "no-dupe-keys": 2,               // http://eslint.org/docs/rules/no-dupe-keys
    "no-duplicate-case": 2,          // http://eslint.org/docs/rules/no-duplicate-case
    "no-empty": 2,                   // http://eslint.org/docs/rules/no-empty
    "no-ex-assign": 2,               // http://eslint.org/docs/rules/no-ex-assign
    "no-extra-boolean-cast": 0,      // http://eslint.org/docs/rules/no-extra-boolean-cast
    "no-extra-semi": 2,              // http://eslint.org/docs/rules/no-extra-semi
    "no-func-assign": 2,             // http://eslint.org/docs/rules/no-func-assign
    "no-inner-declarations": 2,      // http://eslint.org/docs/rules/no-inner-declarations
    "no-invalid-regexp": 2,          // http://eslint.org/docs/rules/no-invalid-regexp
    "no-irregular-whitespace": 2,    // http://eslint.org/docs/rules/no-irregular-whitespace
    "no-obj-calls": 2,               // http://eslint.org/docs/rules/no-obj-calls
    "no-reserved-keys": 2,           // http://eslint.org/docs/rules/no-reserved-keys
    "no-sparse-arrays": 2,           // http://eslint.org/docs/rules/no-sparse-arrays
    "no-unreachable": 2,             // http://eslint.org/docs/rules/no-unreachable
    "use-isnan": 2,                  // http://eslint.org/docs/rules/use-isnan
    "block-scoped-var": 2,           // http://eslint.org/docs/rules/block-scoped-var

/**
 * Best practices
 */
    "consistent-return": 2,          // http://eslint.org/docs/rules/consistent-return
    "curly": [2, "multi-line"],      // http://eslint.org/docs/rules/curly
    "default-case": 2,               // http://eslint.org/docs/rules/default-case
    "dot-notation": [2, {            // http://eslint.org/docs/rules/dot-notation
      "allowKeywords": true
    }],
    "eqeqeq": 2,                     // http://eslint.org/docs/rules/eqeqeq
    "guard-for-in": 2,               // http://eslint.org/docs/rules/guard-for-in
    "no-caller": 2,                  // http://eslint.org/docs/rules/no-caller
    "no-else-return": 2,             // http://eslint.org/docs/rules/no-else-return
    "no-eq-null": 2,                 // http://eslint.org/docs/rules/no-eq-null
    "no-eval": 2,                    // http://eslint.org/docs/rules/no-eval
    "no-extend-native": 2,           // http://eslint.org/docs/rules/no-extend-native
    "no-extra-bind": 2,              // http://eslint.org/docs/rules/no-extra-bind
    "no-fallthrough": 2,             // http://eslint.org/docs/rules/no-fallthrough
    "no-floating-decimal": 2,        // http://eslint.org/docs/rules/no-floating-decimal
    "no-implied-eval": 2,            // http://eslint.org/docs/rules/no-implied-eval
    "no-lone-blocks": 2,             // http://eslint.org/docs/rules/no-lone-blocks
    "no-loop-func": 2,               // http://eslint.org/docs/rules/no-loop-func
    "no-multi-str": 2,               // http://eslint.org/docs/rules/no-multi-str
    "no-native-reassign": 2,         // http://eslint.org/docs/rules/no-native-reassign
    "no-new": 2,                     // http://eslint.org/docs/rules/no-new
    "no-new-func": 2,                // http://eslint.org/docs/rules/no-new-func
    "no-new-wrappers": 2,            // http://eslint.org/docs/rules/no-new-wrappers
    "no-octal": 2,                   // http://eslint.org/docs/rules/no-octal
    "no-octal-escape": 2,            // http://eslint.org/docs/rules/no-octal-escape
    "no-param-reassign": 2,          // http://eslint.org/docs/rules/no-param-reassign
    "no-proto": 2,                   // http://eslint.org/docs/rules/no-proto
    "no-redeclare": 2,               // http://eslint.org/docs/rules/no-redeclare
    "no-return-assign": 2,           // http://eslint.org/docs/rules/no-return-assign
    "no-script-url": 2,              // http://eslint.org/docs/rules/no-script-url
    "no-self-compare": 2,            // http://eslint.org/docs/rules/no-self-compare
    "no-sequences": 2,               // http://eslint.org/docs/rules/no-sequences
    "no-throw-literal": 2,           // http://eslint.org/docs/rules/no-throw-literal
    "no-with": 2,                    // http://eslint.org/docs/rules/no-with
    "radix": 2,                      // http://eslint.org/docs/rules/radix
    "vars-on-top": 2,                // http://eslint.org/docs/rules/vars-on-top
    "wrap-iife": [2, "any"],         // http://eslint.org/docs/rules/wrap-iife
    "yoda": 2,                       // http://eslint.org/docs/rules/yoda

/**
 * Style
 */
    "indent": [2, 2],                // http://eslint.org/docs/rules/
    "brace-style": [2,               // http://eslint.org/docs/rules/brace-style
      "1tbs", {
      "allowSingleLine": true
    }],
    "quotes": [
      2, "single", "avoid-escape"    // http://eslint.org/docs/rules/quotes
    ],
    "camelcase": [2, {               // http://eslint.org/docs/rules/camelcase
      "properties": "never"
    }],
    "comma-spacing": [2, {           // http://eslint.org/docs/rules/comma-spacing
      "before": false,
      "after": true
    }],
    "comma-style": [2, "last"],      // http://eslint.org/docs/rules/comma-style
    "eol-last": 2,                   // http://eslint.org/docs/rules/eol-last
    "func-names": 1,                 // http://eslint.org/docs/rules/func-names
    "key-spacing": [2, {             // http://eslint.org/docs/rules/key-spacing
        "beforeColon": false,
        "afterColon": true
    }],
    "new-cap": [2, {                 // http://eslint.org/docs/rules/new-cap
      "newIsCap": true
    }],
    "no-multiple-empty-lines": [2, { // http://eslint.org/docs/rules/no-multiple-empty-lines
      "max": 2
    }],
    "no-nested-ternary": 2,          // http://eslint.org/docs/rules/no-nested-ternary
    "no-new-object": 2,              // http://eslint.org/docs/rules/no-new-object
    "no-spaced-func": 2,             // http://eslint.org/docs/rules/no-spaced-func
    "no-trailing-spaces": 2,         // http://eslint.org/docs/rules/no-trailing-spaces
    "no-wrap-func": 2,               // http://eslint.org/docs/rules/no-wrap-func
    "no-underscore-dangle": 0,       // http://eslint.org/docs/rules/no-underscore-dangle
    "one-var": [2, "never"],         // http://eslint.org/docs/rules/one-var
    "padded-blocks": [2, "never"],   // http://eslint.org/docs/rules/padded-blocks
    "semi": [2, "always"],           // http://eslint.org/docs/rules/semi
    "semi-spacing": [2, {            // http://eslint.org/docs/rules/semi-spacing
      "before": false,
      "after": true
    }],
    "space-after-keywords": 2,       // http://eslint.org/docs/rules/space-after-keywords
    "space-before-blocks": 2,        // http://eslint.org/docs/rules/space-before-blocks
    "space-before-function-paren": [2, "never"], // http://eslint.org/docs/rules/space-before-function-paren
    "space-infix-ops": 2,            // http://eslint.org/docs/rules/space-infix-ops
    "space-return-throw-case": 2,    // http://eslint.org/docs/rules/space-return-throw-case
    "spaced-line-comment": 2,        // http://eslint.org/docs/rules/spaced-line-comment
  }
}


================================================
FILE: .gitignore
================================================
node_modules
npm-debug.log
build


================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
  - "0.12"


================================================
FILE: CHANGELOG.md
================================================
# ChangeLog

### v1.1.0

Add support to use inside Meteor. Basically, we turn off plugin when running inside Meteor.
See: [a43785d](https://github.com/mantrajs/babel-root-slash-import/commit/90d768668fb589583657aa949683149bc6d33020)

### v1.0.0

Forked <https://github.com/michaelzoidl/babel-root-import> use `/` instead of '~/' to define the root.
This is to go with the Meteor's ES2015 module implementation.


================================================
FILE: LICENSE
================================================
The MIT License (MIT)

Copyright (c) 2015 Michael J. Zoidl

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.



================================================
FILE: README.md
================================================
# Babel Root Import
Babel plugin to change the behaviour of `import` to root based paths.<br>

## Example
```javascript
// Usually
import SomeExample from '../../../some/example.js';

// With Babel-Root-Importer
import SomeExample from '/some/example.js';
```

## Install
```
npm install babel-root-slash-import --save-dev
```

## Use
Add a `.babelrc` file and write:
```javascript
{
  "plugins": [
    "babel-root-slash-import"
  ]
}
```
or pass the plugin with the plugins-flag on CLI
```
babel-node myfile.js --plugins babel-root-slash-import
```

## Extras
If you want a custom root because for example all your files are in the src/js folder you can define this in your `.babelrc` file
```javascript
{
  "plugins": [
    ["babel-root-slash-import", {
      "rootPathSuffix": "src/js"
    }]
  ]
}
```

## Motivate
If you like this project just give it a star :) I like stars.


================================================
FILE: config/mocha.js
================================================
import chai from 'chai';
import sinon from 'sinon';

global.chai = chai;
global.expect = chai.expect;
global.sinon = sinon;


================================================
FILE: index.js
================================================
global.rootPath = process.cwd();
module.exports = require('./build/index.js');


================================================
FILE: package.json
================================================
{
  "name": "babel-root-slash-import",
  "version": "1.1.0",
  "description": "Babel Plugin to enable relative root-import",
  "author": "Arunoda Susiripala <arunoda@kadira.io>",
  "license": "MIT",
  "main": "index.js",
  "files": [
    "index.js",
    "build"
  ],
  "repository": "mantrajs/babel-root-slash-import",
  "scripts": {
    "test": "mocha test/*.spec.js --require config/mocha.js --compilers js:babel-core/register",
    "test-watch": "mocha test/*.spec.js --require config/mocha.js --compilers js:babel-core/register --watch",
    "lint-js": "eslint plugin",
    "compile": "babel -d build/ plugin/"
  },
  "dependencies": {
    "babel": "^6.1.18"
  },
  "devDependencies": {
    "babel-core": "^6.2.1",
    "babel-eslint": "^4.0.6",
    "babel-cli": "6.x.x",
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-stage-1": "^6.1.18",
    "chai": "^3.2.0",
    "eslint": "^1.1.0",
    "mocha": "^2.2.5",
    "sinon": "^1.15.4"
  }
}


================================================
FILE: plugin/helper.js
================================================
export default function(path) {
  class BabelRootImportHelper {

    root = global.rootPath || process.cwd();

    transformRelativeToRootPath(path, rootPathSuffix) {
      if (this.hasRoot(path)) {
        const withoutRoot = path.substring(1, path.length);
        return `${this.root}${rootPathSuffix ? rootPathSuffix : ''}/${withoutRoot}`;
      }
      if (typeof path === 'string') {
        return path;
      }
      throw new Error('ERROR: No path passed');
    }

    hasRoot(string) {
      let containsTilde = false;

      if (typeof string !== 'string') {
        return false;
      }

      const firstChar = string.substring(0, 1);
      return firstChar === '/';
    }
  }

  return new BabelRootImportHelper();
}


================================================
FILE: plugin/index.js
================================================
import BabelRootImportHelper from './helper';

export default function({ types: t }) {
  class BabelRootImport {
    constructor() {
      const that = this;
      return {
        visitor: {
          ImportDeclaration(path, state) {
            const givenPath = path.node.source.value;

            var rootPathSuffix = state && state.opts && typeof state.opts.rootPathSuffix === 'string' ?
            '/' + state.opts.rootPathSuffix.replace(/^(\/)|(\/)$/g, '') :
                '';

            if(BabelRootImportHelper().hasRoot(givenPath)) {
              path.node.source.value = BabelRootImportHelper().transformRelativeToRootPath(givenPath, rootPathSuffix);
            }
          }
        }
      };
    }
  }

  // Here's we detect the use of Meteor and send a dummy plugin.
  // That's because, Meteor already do this for us.
  //  global.meteorBabelHelpers is something we can see when
  //  running inside Meteor.
  if (global.meteorBabelHelpers) {
    return {
      visitor: {}
    };
  }

  return new BabelRootImport();
}


================================================
FILE: test/helper.spec.js
================================================
import BabelRootImportHelper from '../plugin/helper';

describe('Babel Root Import - Helper', () => {

  describe('transformRelativeToRootPath', () => {
      it('returns a string', () => {
        console.log(BabelRootImportHelper().transformRelativeToRootPath(''));
        const func = BabelRootImportHelper().transformRelativeToRootPath('');
        expect(func).to.be.a('string');
      });

      it('transforms given path relative root-path', () => {
        const rootPath = `${process.cwd()}/some/path`;
        const result = BabelRootImportHelper().transformRelativeToRootPath('/some/path');
        expect(result).to.equal(rootPath);
      });

      it('throws error if no string is passed', () => {
        expect(() => {
          BabelRootImportHelper().transformRelativeToRootPath();
        }).to.throw(Error);
      });
  });

  describe('Class', () => {
    it('returns the root path', () => {
      const rootByProcess = process.cwd();
      expect(BabelRootImportHelper().root).to.equal(rootByProcess);
    });
  });

  describe('transformRelativeToRootPath', () => {
    it('returns a string', () => {
      const func = BabelRootImportHelper().transformRelativeToRootPath('');
      expect(func).to.be.a('string');
    });

    it('transforms given path relative root-path', () => {
      const rootPath = `${process.cwd()}/some/path`;
      const result = BabelRootImportHelper().transformRelativeToRootPath('/some/path');
      expect(result).to.equal(rootPath);
    });

    it('throws error if no string is passed', () => {
      expect(() => {
        BabelRootImportHelper().transformRelativeToRootPath();
      }).to.throw(Error);
    });
  });


  describe('hasRoot', () => {
    it('returns a boolean', () => {
      const func = BabelRootImportHelper().hasRoot();
      expect(func).to.be.a('boolean');
    });

    it('check if the string has "/" at the beginning', () => {
      const withRoot = BabelRootImportHelper().hasRoot('/path');
      const withoutRoot = BabelRootImportHelper().hasRoot('./some/path');
      expect(withoutRoot).to.be.false;
      expect(withRoot).to.be.true;
    });

    it('returns false if no string passed', () => {
      const nothingPassed = BabelRootImportHelper().hasRoot();
      const wrongTypePassed = BabelRootImportHelper().hasRoot([]);
      expect(nothingPassed).to.be.false;
      expect(wrongTypePassed).to.be.false;
    });
  });
});


================================================
FILE: test/plugin.spec.js
================================================
import BabelRootImportPlugin from '../plugin';
import * as babel from 'babel-core';

describe('Babel Root Import - Plugin', () => {
  describe('Babel Plugin', () => {
    it('transforms the relative path into an absolute path', () => {
      const targetRequire = `${process.cwd()}/some/example.js`;
      const transformedCode = babel.transform("import SomeExample from '/some/example.js';", {
        plugins: [BabelRootImportPlugin]
      });

      expect(transformedCode.code).to.contain(targetRequire);
    });

    it('transforms the relative path into an absolute path with the configured root-path', () => {
      const targetRequire = `some/custom/root/some/example.js`;
      const transformedCode = babel.transform("import SomeExample from '/some/example.js';", {
        plugins: [[
          BabelRootImportPlugin, {
            rootPathSuffix: 'some/custom/root'
          }
        ]]
      });

      expect(transformedCode.code).to.contain(targetRequire);
    });
  });
});
gitextract_07hnpfxp/

├── .babelrc
├── .eslintrc
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── LICENSE
├── README.md
├── config/
│   └── mocha.js
├── index.js
├── package.json
├── plugin/
│   ├── helper.js
│   └── index.js
└── test/
    ├── helper.spec.js
    └── plugin.spec.js
Condensed preview — 14 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (19K chars).
[
  {
    "path": ".babelrc",
    "chars": 38,
    "preview": "{\n  \"presets\": [\"es2015\",\"stage-1\"]\n}\n"
  },
  {
    "path": ".eslintrc",
    "chars": 8929,
    "preview": "{\n  \"parser\": \"babel-eslint\",\n  \"env\": {\n    \"browser\": true,\n    \"node\": true\n  },\n  \"ecmaFeatures\": {\n    \"arrowFuncti..."
  },
  {
    "path": ".gitignore",
    "chars": 33,
    "preview": "node_modules\nnpm-debug.log\nbuild\n"
  },
  {
    "path": ".travis.yml",
    "chars": 38,
    "preview": "language: node_js\nnode_js:\n  - \"0.12\"\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 411,
    "preview": "# ChangeLog\n\n### v1.1.0\n\nAdd support to use inside Meteor. Basically, we turn off plugin when running inside Meteor.\nSee..."
  },
  {
    "path": "LICENSE",
    "chars": 1084,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2015 Michael J. Zoidl\n\nPermission is hereby granted, free of charge, to any person..."
  },
  {
    "path": "README.md",
    "chars": 881,
    "preview": "# Babel Root Import\nBabel plugin to change the behaviour of `import` to root based paths.<br>\n\n## Example\n```javascript..."
  },
  {
    "path": "config/mocha.js",
    "chars": 124,
    "preview": "import chai from 'chai';\nimport sinon from 'sinon';\n\nglobal.chai = chai;\nglobal.expect = chai.expect;\nglobal.sinon = sin..."
  },
  {
    "path": "index.js",
    "chars": 79,
    "preview": "global.rootPath = process.cwd();\nmodule.exports = require('./build/index.js');\n"
  },
  {
    "path": "package.json",
    "chars": 950,
    "preview": "{\n  \"name\": \"babel-root-slash-import\",\n  \"version\": \"1.1.0\",\n  \"description\": \"Babel Plugin to enable relative root-impo..."
  },
  {
    "path": "plugin/helper.js",
    "chars": 732,
    "preview": "export default function(path) {\n  class BabelRootImportHelper {\n\n    root = global.rootPath || process.cwd();\n\n    trans..."
  },
  {
    "path": "plugin/index.js",
    "chars": 1044,
    "preview": "import BabelRootImportHelper from './helper';\n\nexport default function({ types: t }) {\n  class BabelRootImport {\n    con..."
  },
  {
    "path": "test/helper.spec.js",
    "chars": 2415,
    "preview": "import BabelRootImportHelper from '../plugin/helper';\n\ndescribe('Babel Root Import - Helper', () => {\n\n  describe('trans..."
  },
  {
    "path": "test/plugin.spec.js",
    "chars": 992,
    "preview": "import BabelRootImportPlugin from '../plugin';\nimport * as babel from 'babel-core';\n\ndescribe('Babel Root Import - Plugi..."
  }
]

About this extraction

This page contains the full source code of the mantrajs/babel-root-slash-import GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 14 files (17.3 KB), approximately 5.0k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!