Import management

JavaScript pattern

Grit includes standard patterns for declaratively adding, removing, and updating imports.

Ensures, replaces and removes specified imports

BEFORE
import { keep } from 'keepable';

import { orderBy } from 'underscore';
import fetch from 'elsewhere';
import { fetch } from 'node-fetch';
import { fetch, more } from 'node-fetch';
import fetch from 'node-fetch';
import defaultNotNamedFetch, { fetch } from 'node-fetch';

console.log(orderBy([1, 2, 3]));

console.log(v4());

fetch();
AFTER
import { keep } from 'keepable';
import { orderBy } from 'lodash';
import { v4 } from 'uuid';

import fetch from 'elsewhere';
import { more } from 'node-fetch';
import defaultNotNamedFetch from 'node-fetch';

console.log(orderBy([1, 2, 3]));

console.log(v4());

fetch();

Ignores Shebang

BEFORE
#!/usr/bin/env node

import { orderBy } from 'underscore';
import fetch from 'elsewhere';
import { fetch } from 'node-fetch';
import { fetch, more } from 'node-fetch';
import fetch from 'node-fetch';

console.log(orderBy([1, 2, 3]));

console.log(v4());

fetch();
AFTER
#!/usr/bin/env node
import { orderBy } from 'lodash';
import { v4 } from 'uuid';

import fetch from 'elsewhere';
import { more } from 'node-fetch';

console.log(orderBy([1, 2, 3]));

console.log(v4());

fetch();

Ensures a React import

From https://docs.grit.io/guides/imports:

BEFORE
import _ from 'lodash';

class Button extends Component {
  // ...
}
AFTER
import _ from 'lodash';
import { Component } from 'React';

class Button extends Component {
  // ...
}

Leaves correct imports alone

BEFORE
import { orderBy } from 'lodash';

orderBy([1, 2, 3]);
AFTER
import { orderBy } from 'lodash';

orderBy([1, 2, 3]);

Inserts imports when none exist

BEFORE
console.log('this is a test');

class Button extends Component {
  // ...
}
AFTER
import { Component } from 'React';

console.log('this is a test');

class Button extends Component {
  // ...
}

Standalone add_import

The add_import($name, $source) predicate can be used to add an import to a file.

BEFORE
final_case('this is a test');
AFTER
import { just_ensure } from 'this_place';

final_case('this is a test');