// @create-indexexport { default as bar } from './bar.js';export { default as baz } from './baz.js';export { default as foo } from './foo.js';
Usage
Using CLI Program
npm install create-indexcreate-index --helpOptions: --recursive, -r Create/update index files recursively. Halts on any unsafe "index.js" files. [boolean] [default: false] --ignoreUnsafe, -i Ignores unsafe "index.js" files instead of halting. [boolean] [default: false] --ignoreDirectories, -d Ignores importing directories into the index file, even if they have a safe "index.js". [boolean] [default: false] --update, -u Updates
Using create-index Programmatically
import { writeIndex} from 'create-index';/** * @type {Function} * @param {Array<string>} directoryPaths * @throws {Error} Directory "..." does not exist. * @throws {Error} "..." is not a directory. * @throws {Error} "..." unsafe index. * @returns {boolean} */writeIndex;
Note that the writeIndex function is synchronous.
import { findIndexFiles} from 'create-index';/** * @type {Function} * @param {string} directoryPath * @returns {Array<string>} List of directory paths that have create-index index file. */findIndexFiles;
import { writeIndex} from 'create-index';gulp.task('create-index', () => { writeIndex(['./target_directory']);});
Note that the writeIndex function is synchronous.
Implementation
create-index program will look into the target directory.
If there is no ./index.js, it will create a new file, e.g.
// @create-index
Created index file must start with // @create-index\n\n. This is used to make sure that create-index does not accidentally overwrite your local files.
If there are sibling files, index file will import them and export, e.g.
children-directories-and-files git:(master) ✗ ls -lahtotal 0drwxr-xr-x 5 gajus staff 170B 6 Jan 15:39 .drwxr-xr-x 10 gajus staff 340B 6 Jan 15:53 ..drwxr-xr-x 2 gajus staff 68B 6 Jan 15:29 bardrwxr-xr-x 2 gajus staff 68B 6 Jan 15:29 foo-rw-r--r-- 1 gajus staff 0B 6 Jan 15:29 foo.js
Given the above directory contents, ./index.js will be:
// @create-indeximport { default as bar } from './bar';import { default as foo } from './foo.js';export { bar, foo};
When file has the same name as a sibling directory, file import takes precedence.
Directories that do not have ./index.js in themselves will be excluded.
When run again, create-index will update existing ./index.js if it starts with // @create-index\n\n.
If create-index is executed against a directory that contains ./index.js, which does not start with // @create-index\n\n, an error will be thrown.
Ignore files on --update
create-index can ignore files in a directory if ./index.js contains special object with defined ignore property which takes an array of regular expressions defined as strings, e.g.