Small Babel plugin allowing to use shorthand imports.
It generates import's identifier from file name (without extension), so all line can be written in shorter version as import "path/to/the/file"
. It also works with NPM modules.
Plugin requires Babel 7 and it may cause conflicts with Webpack's methods of including styles and other files.
$ npm install --save-dev babel-plugin-short-import
.babelrc
{
"plugins": [
"babel-plugin-short-import",
{
"importAsNamespace": false,
"useCamelCase": false
}
]
}
$ babel --plugins babel-plugin-short-import script.js
require('babel-core').transform('code', {
plugins: [
'babel-plugin-short-import',
{
importAsNamespace: false,
useCamelCase: false
}
]
});
-
importAsNamespace
If
false
(default) it will behave likeimport file from "./path/file.js"
.Otherwise it will import all namespace -
import * as file from "./path/file.js"
. -
useCamelCase
If
false
(default) it will replace invalid characters in file name with underscore ( _ ) likeimport my_file from "./path/my-file.js
.Otherwise it will apply camel case -
import * as myFile from "./path/my-file.js"
.
path/to/the/file.js or @vendor/some-module
export const test1 = "Test 1";
export const test2 = { test: 2 };
export default "Default test";
Configured with { "importAsNamespace": false }
Import in this example is an equivalent of import file from "path/to/the/file.js"
import "path/to/the/file.js";
console.log(file.test1); // undefined
console.log(file.test2); // undefined
console.log(file); // "Default test"
Configured with { "importAsNamespace": true }
Import in this example is an equivalent of import * as file from "path/to/the/file.js"
import "path/to/the/file.js";
console.log(file.test1); // "Test 1"
console.log(file.test2); // { "test": 2 }
console.log(file); // { "test1": "Test 1", "test2": { "test": 2 }, "default": "Default test" }
Configured with { "importAsNamespace": true, "useCamelCase": true }
import "@vendor/some-module";
console.log(someModule.test1); // "Test 1"
console.log(someModule.test2); // { "test": 2 }
console.log(someModule.default); // "Default test"