Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@trivago/prettier-plugin-sort-imports

Package Overview
Dependencies
Maintainers
3
Versions
36
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@trivago/prettier-plugin-sort-imports - npm Package Compare versions

Comparing version 1.0.1 to 1.1.0

6

lib/src/index.js

@@ -25,2 +25,8 @@ "use strict";

},
importOrderSeparation: {
type: 'boolean',
category: 'Global',
default: false,
description: 'Should imports be separated by new line ?',
},
};

@@ -27,0 +33,0 @@ module.exports = {

29

lib/src/preprocessor.js

@@ -7,3 +7,2 @@ "use strict";

exports.preprocessor = void 0;
var generator_1 = __importDefault(require("@babel/generator"));
var parser_1 = require("@babel/parser");

@@ -14,3 +13,3 @@ var traverse_1 = __importDefault(require("@babel/traverse"));

function preprocessor(code, options) {
var importOrder = options.importOrder;
var importOrder = options.importOrder, importOrderSeparation = options.importOrderSeparation;
var importNodes = [];

@@ -29,21 +28,8 @@ var ast = parser_1.parse(code, {

});
var thirdPartyImports = utils_1.getSortedNodesNotInTheImportOrder(importNodes, importOrder);
var localImports = utils_1.getSortedNodesByImportOrder(importNodes, importOrder);
var thirdPartyImports = utils_1.getSortedNodesNotInTheImportOrder(importNodes, importOrder);
var newAst = types_1.file({
type: 'Program',
body: thirdPartyImports.concat(localImports),
directives: [],
sourceType: 'module',
interpreter: null,
sourceFile: '',
leadingComments: [],
innerComments: [],
trailingComments: [],
start: 0,
end: 0,
loc: {
start: { line: 0, column: 0 },
end: { line: 0, column: 0 },
},
});
var thirdPartyImportsAsCode = utils_1.getCodeFromAst(thirdPartyImports);
var localImportsAsCode = localImports
.map(utils_1.getCodeFromAst)
.join(utils_1.handleImportSeparation(importOrderSeparation));
var importsStart = importNodes[0]

@@ -56,6 +42,7 @@ ? importNodes[0].start !== null

var initialCodeBlock = modifiedCode.substring(0, importsStart);
var middleCodeBlock = generator_1.default(newAst).code;
var middleCodeBlock = utils_1.getAllGeneratedImportCodeTogether(thirdPartyImportsAsCode, localImportsAsCode, importOrderSeparation);
var endCodeBlock = modifiedCode.substring(importsStart);
debugger;
return "" + initialCodeBlock + middleCodeBlock + endCodeBlock;
}
exports.preprocessor = preprocessor;
"use strict";
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -6,16 +13,32 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

Object.defineProperty(exports, "__esModule", { value: true });
exports.removeImportsFromOriginalCode = exports.getSortedNodesNotInTheImportOrder = exports.getSortedNodesByImportOrder = void 0;
exports.getAllGeneratedImportCodeTogether = exports.getNewLine = exports.handleImportSeparation = exports.getCodeFromAst = exports.removeImportsFromOriginalCode = exports.getSortedNodesNotInTheImportOrder = exports.getSortedNodesByImportOrder = void 0;
// we do not have types for javascript-natural-sort
//@ts-ignore
var javascript_natural_sort_1 = __importDefault(require("javascript-natural-sort"));
var generator_1 = __importDefault(require("@babel/generator"));
var types_1 = require("@babel/types");
/**
* This function checks that specified string exists in the specified list.
*/
var isSimilarTextExistInArray = function (arr, text) {
return arr.some(function (element) { return text.match(new RegExp(element)) !== null; });
};
/**
* This function returns all the nodes which are in the importOrder array.
* The plugin considered these import nodes as local import declarations.
*/
exports.getSortedNodesByImportOrder = function (nodes, order) {
return order.reduce(function (res, val) {
var x = nodes.filter(function (node) { return node.source.value.match(new RegExp(val)) !== null; });
x.sort(function (a, b) { return javascript_natural_sort_1.default(a.source.value, b.source.value); });
return res.concat(x);
if (x.length > 0) {
x.sort(function (a, b) { return javascript_natural_sort_1.default(a.source.value, b.source.value); });
return __spreadArrays(res, [x]);
}
return res;
}, []);
};
/**
* This function returns all the nodes which are not in the importOrder array.
* The plugin considered these import nodes as third party import declarations.
*/
exports.getSortedNodesNotInTheImportOrder = function (nodes, order) {

@@ -26,2 +49,6 @@ var x = nodes.filter(function (node) { return !isSimilarTextExistInArray(order, node.source.value); });

};
/**
* When we get all the imports from the code, we remove these import statements
* from the original code which is passed to prettier preprocessor.
*/
exports.removeImportsFromOriginalCode = function (code, nodes) {

@@ -39,1 +66,38 @@ var text = code;

};
/**
* This function generate a code string from the passed nodes.
*/
exports.getCodeFromAst = function (node) {
var ast = types_1.file({
type: 'Program',
body: node,
directives: [],
sourceType: 'module',
interpreter: null,
sourceFile: '',
leadingComments: [],
innerComments: [],
trailingComments: [],
start: 0,
end: 0,
loc: {
start: { line: 0, column: 0 },
end: { line: 0, column: 0 },
},
});
return generator_1.default(ast).code;
};
exports.handleImportSeparation = function (isNewLine) {
return isNewLine ? '\n\n' : '';
};
exports.getNewLine = function () { return '\n'; };
/**
* This function stitches all the imports together. If import separation is
* enabled then this function adds new line accordingly.
*/
exports.getAllGeneratedImportCodeTogether = function (thirdPartyImportsAsCode, localImportsAsCode, importOrderSeparation) {
if (thirdPartyImportsAsCode.length > 0) {
return "" + thirdPartyImportsAsCode + exports.handleImportSeparation(importOrderSeparation) + localImportsAsCode + exports.handleImportSeparation(importOrderSeparation) + exports.getNewLine();
}
return "" + localImportsAsCode + exports.handleImportSeparation(importOrderSeparation) + exports.getNewLine();
};
{
"name": "@trivago/prettier-plugin-sort-imports",
"version": "1.0.1",
"version": "1.1.0",
"description": "A prettier plugins to sort imports in provided RegEx order",

@@ -16,3 +16,3 @@ "main": "lib/src/index.js",

"type-check": "tsc --noEmit",
"prepare": "npm run compile && npm run test"
"prepublishOnly": "npm run compile && npm run test"
},

@@ -19,0 +19,0 @@ "keywords": [

@@ -5,4 +5,6 @@ # Prettier plugin sort imports

#### Install
![import order gif](./import-sort.gif)
### Install
npm

@@ -20,3 +22,3 @@

#### Usage
### Usage

@@ -34,15 +36,21 @@ Add an order in prettier config file.

"importOrder": ["^@core/(.*)$", "^@server/(.*)$", "^@ui/(.*)$", "^[./]"],
"importOrderSeparation": true,
}
```
#### API
### APIs
**importOrder**: A collection of regular expressions in string format. The plugin
#### `importOrder`
A collection of regular expressions in string format. The plugin
uses [`new RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
to evaluate RegEx. E.g. `node.source.value.match(new RegExp(val))` Here, `val`
to evaluate regular expression. E.g. `node.source.value.match(new RegExp(val))` Here, `val`
is the string provided in import order.
#### `importOrderSeparation`
A boolean value to enable or disable the new line separation
between sorted import declarations. The separation takes place according to `importOrder`.
#### How does import sort work ?
### How does import sort work ?
The plugin extracts the imports which are defined in `importOrder`.

@@ -57,5 +65,5 @@ These imports are _local imports_. The imports which are not part of the

#### FAQ / Troubleshooting
### FAQ / Troubleshooting
##### Q. How can I add the RegEx imports in the `importOrder` list ?
#### Q. How can I add the RegEx imports in the `importOrder` list ?
You can define the RegEx in the `importOrder`. For

@@ -85,3 +93,3 @@ example if you want to sort the following imports:

##### Q. How can I run examples in this project ?
#### Q. How can I run examples in this project ?
There is a _examples_ directory. The examples file can be formatted by using

@@ -95,3 +103,3 @@ `npm run example` command.

#### Maintainer
### Maintainer

@@ -98,0 +106,0 @@ | [Ayush Sharma](https://github.com/ayusharma)

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc