Creates ES6 ./index.js file in target directories that imports and exports all sibling files and directories.

Overview

create-index

NPM version Travis build status js-canonical-style

create-index program creates (and maintains) ES6 ./index.js file in target directories that imports and exports sibling files and directories.

Example

> tree ./
./
├── bar.js
└── foo.js

0 directories, 2 files

> create-index ./
[13:17:34] Target directories [ './' ]
[13:17:34] Update index: false
[13:17:34] ./index.js [created index]
[13:17:34] Done

> tree
.
├── bar.js
├── foo.js
└── index.js

0 directories, 3 files

This created index.js with:

// @create-index

export { default as bar } from './bar.js';
export { default as foo } from './foo.js';

Lets create a new file and re-run create-index:

> touch baz.js
> tree ./
./
├── bar.js
├── baz.js
├── foo.js
└── index.js

0 directories, 4 files

> create-index ./
[13:21:55] Target directories [ './' ]
[13:21:55] Update index: false
[13:21:55] ./index.js [updated index]
[13:21:55] Done

This have updated index.js file:

// @create-index

export { 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-index

create-index --help

Options:
  --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 only previously created index files
                           (recursively).             [boolean] [default: false]
  --banner                 Add a custom banner at the top of the index file
                                                                        [string]
  --extensions, -x         Allows some extensions to be parsed as valid source.
                           First extension will always be preferred to homonyms
                           with another allowed extension.
                                                       [array] [default: ["js"]]
  --outputFile, -o         Output file            [string] [default: "index.js"]                                                      [array] [default: ["js"]]

Examples:
  create-index ./src ./src/utilities      Creates or updates an existing
                                          create-index index file in the target
                                          (./src, ./src/utilities) directories.
  create-index --update ./src ./tests     Finds all create-index index files in
                                          the target directories and descending
                                          directories. Updates found index
                                          files.
  create-index ./src --extensions js jsx  Creates or updates an existing
                                          create-index index file in the target
                                          (./src) directory for both .js and
                                          .jsx extensions.

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;

Gulp

Since Gulp can ran arbitrary JavaScript code, there is no need for a separate plugin. See Using create-index Programmatically.

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 -lah
total 0
drwxr-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 bar
drwxr-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-index

import { 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.

> cat index.js
// @create-index {"ignore": ["/baz.js$/"]}
> tree ./
./
├── bar.js
├── baz.js
├── foo.js
└── index.js

0 directories, 4 files

Given the above directory contents, after running create-index with --update flag, ./index.js will be:

// @create-index {"ignore": ["/baz.js$/"]}

import { default as bar } from './bar.js';
import { default as foo } from './foo.js';

export {
    bar,
    foo
};
Comments
  • Does not work with filename using dash.

    Does not work with filename using dash.

    Hi,

    I tried your project on a directory from our project and it seems that all files that have a default export but a dash in their filename are ignored. All files without dash are correctly added to the index.js file.

    Thanks.

    question 
    opened by moimael 16
  • (Feature) Add custom template function

    (Feature) Add custom template function

    • [x] Tests and lint pass
    • [x] Added new test

    This pull request adds the ability to customize the output of create-index, to create different kinds of exports:

    writeIndex(['./target_directory'], {}, (varName, fileName) => `export * as ${varName} from './${fileName}`);
    
    // export * as Example from './Example';
    

    Doing so allows the customization for a couple uses cases I've experienced personally and have seen in the issues here.

    This change only affects the API. I was not sure what to do for the client, I would suppose a good way to add support would to add a --template file/path.js flag where the JS file must export a function. @gajus please let me know if you have any thoughts on that matter.

    Cheers!

    enhancement 
    opened by coleturner 12
  • Make target file extension configurable

    Make target file extension configurable

    I use .jsx in my project (for ReactJS) so this currently will not work on my components folder.

    I could submit a pull request but wondered if you want to support user-configured extensions.

    enhancement 
    opened by gausie 8
  • Generated code style

    Generated code style

    Currently, create-index files are identified by the string:

    'create index';
    

    This string is not linter friendly since it is not an assignment nor call. As far as I know, there is no way to define new directives like 'use strict'.

    What about using a comment like eslint, flow type, and others:

    /* create-index */
    

    or

    /* @create-index */
    

    The latter would give a little more certainty when parsing comments for the flag. A flag like this in general would also allow parsing options following the flag as with eslint for instance.

    Thoughts?

    enhancement 
    opened by levithomason 8
  • Update: Added --extension/-x parameter overwrite default .js extension

    Update: Added --extension/-x parameter overwrite default .js extension

    As seen in #6 it is important to allow people to safely choose what extension they want to support.

    I've created this PR to allow people to create-index over jsx and js, but it can be extended to anything. To achieve that readDirectory accepts extensions in its options. If not specified, it is defaulted to 'js'.

    The main change is that file extension is tested against all of those extension to see if the file is eligible for export. Second important feature is that removeDuplicates also search for files that are homonyms, and will always discard homonyms with extensions matching the first listed. So if you put extensions = ['js', 'jsx'] you'll always let your js file win over jsx files. It works as for homonyms directories.

    enhancement 
    opened by Guibod 7
  • feat: add a default export

    feat: add a default export

    This adds a default export object containing all named exports.

    Eg.:

    // @create-index
    
    export king from './king.js'
    export queen from './queen'
    export default {
      king,
      queen
    }
    

    Fixes #11

    Keeps camelCase support from #16

    opened by laggingreflex 6
  • [bug] can't read file or folder with

    [bug] can't read file or folder with "-"?

    Hello,

    I wanted to create an index of some files or folders with "-" and I saw that an empty index with just the banner was created.

    So I tried to rename my folders or files and now it works.

    image

    As you can see, only the one without "-" worked.

    question 
    opened by kud 5
  • Feat(#31): Add ignore option

    Feat(#31): Add ignore option

    • This commit add functionality to ignore files based on provided regexps.

    • in index.js config must be specified as below

      // @create-index {"ignore":["/foo.js"]}

    opened by hinok 5
  • fix: logging

    fix: logging

    edit: original PR withdrawn before:

    [03:26:10] <...>\src\utils\index.js [index have not changed]
    [03:26:10] <...>\src\methods\index.js [index have not changed]
    [03:26:10] <...>\src\utils\prompt\index.js [index have not changed]
    [03:26:10] <...>\src\utils\help\index.js [index have not changed]
    [03:26:10] <...>\src\utils\error\index.js [index have not changed]
    

    after:

    [03:22:25] [index created] <...>\src\utils\index.js
    [03:22:25] [index is same] <...>\src\methods\index.js
    [03:22:25] [index is same] <...>\src\utils\prompt\index.js
    [03:22:26] [index is same] <...>\src\utils\help\index.js
    [03:22:26] [index updated] <...>\src\utils\error\index.js
    
    enhancement 
    opened by laggingreflex 5
  • Add option to uppercase first char of export

    Add option to uppercase first char of export

    I'd like to be able to use this for mongoose models. Typically the models are imported with their first char capitalised such as import {Comment, Post, User} from 'models'; from what I can tell the vars are exported using the filenames and I'd rather not have to rename my files Post.js, etc. as it will clash with my linting rules for file names.

    enhancement question 
    opened by OmgImAlexis 4
  • Feature request: Excluding specific files

    Feature request: Excluding specific files

    Hey, It's just proposal of a new feature that could be very handy.

    I would like to exclude some files which are added to generated index.js files, why? I have a folder /icons witch contains all my icons (each icon is a react component). In this folder I have also stories.js file (I'm using react-storybook). Now stories.js is always added to the end of the file and my storybook is broken.

    I think that it could work also for other people in other more advanced cases. I could implement it and add PR but before I would like to talk about proposed solutions.

    1. Using a "special comment" in generated index.js file

    // @create-index
    // @create-index-ignore: [/stories.(js)$/]
    
    export Abc from './Abc.js';
    export Zxc from './Zxc.js';
    export Qwe from './Qwe.js';
    

    .2 Using a "special configuration file" .create-index inside a specific directory

    .create-index

    {
      ignore: [
        /stories.(js)$/
      ]
    }
    
    enhancement 
    opened by hinok 4
  • Use with typescript, add webpack plugin

    Use with typescript, add webpack plugin

    I've forked this repo to add typescript support, along with a corresponding webpack plugin which can automatically re-write index files on a recompile

    https://github.com/sarink/ts-create-index

    opened by sarink 2
  • Support creating index with default export

    Support creating index with default export

    Currently, this plugin only supports creating an index with named exports. I need an index file with a default-exported object.

    Example:

    import foo from './foo.js';
    import bar from './bar.js';
    import _3_x_recommended from './3-x-recommended.js'; // note unsafe variable name needs to be tweaked
    
    export default { 
      foo, 
      bar, 
      '3-x-recommended': _3_x_recommended
    };
    

    I see this functionality is in a forked version of this tool: https://github.com/tjjfvi/create-index-better#modes

    // @create-index {"mode":"default{}"}

    import foo from './foo.js'; import bar from './bar.js'; export default { foo, bar };

    Has it been considered for the original create-index? @tjjfvi would you consider upstreaming this functionality (and presumably any other improvements from the fork)?

    enhancement 
    opened by bmish 9
  • Adding flags to use implicit defaults and wildcard folders

    Adding flags to use implicit defaults and wildcard folders

    I found an issue in the recurse logic. This tool creates a bunch of named exports. It can recurse. It grabs default exports normally. This means it has issues recursing itself because it's not grabbing the child folder's named exports. It's resolved by using wildcard characters on folders. I don't want to mess with existing stuff, so it's an optional flag.

    Also, I added a flag so defaults could be made implicit instead of explicit. More OCD than anything.

    Thanks for the great tool and if you don't want to incorporate this stuff, let me know. Thanks!

    Also, I can change the file permissions and gitignore back np.

    opened by toddtarsi 4
  • Add --output option to configure output file

    Add --output option to configure output file

    Currently always outputs as index,js but in a typescript project I would like index.ts

    I might even want to change the name from index to something else.

    enhancement 
    opened by corbanbrook 3
  • Importing created subdirectory index files

    Importing created subdirectory index files

    Hello! Thanks so much for the great work on create-index! I apologize if this has been brought up before, after some time of searching the issues and pull requests I could not find mention of it.

    I have a library project with some deeper source folders and much to my delight create-index does indeed create index.js files exactly how I was looking for, short of one thing. When creating a parent folder's index.js and using the recurse into subfolders option the parent folder's index.js will not import the child folder's. To further call the inconsistency out, subsequent runs of create-index will properly import the child folder's now created index.js.

    I'd be happy to submit a PR if this seems like a feature that should be included, especially if it's something someone unfamiliar with the source can easily jump in and do, say if it's a matter of swapping the order of generation.

    Thank you for your time!

    enhancement 
    opened by yoiang 5
  • Include folder name in banner

    Include folder name in banner

    Is there any way to add current folder name in banner parameters? something like $folder translates to current folder index is created would be really helpful. This way we can add something similar to /** @namespace $folder */ in banner for jsDoc.

    opened by SerdarSanri 0
Releases(v2.6.0)
Owner
Gajus Kuizinas
Software architect. Passionate about JavaScript, React, GraphQL, Redux. Active open-source contributor.
Gajus Kuizinas
A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.

InversifyJS A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript. About InversifyJS is a ligh

inversify 9.5k Jan 4, 2023
Task toolkit. For when `npm run` isn't enough and everything else is too much.

For when npm run isn't enough and everything else is too much. Ygor is a no-frills toolkit consisting of a task runner and a file transformer. Enjoy a

Shannon Moeller 68 Nov 12, 2022
Simple build system and CLI for AMX Mod X projects

?? AMXXPack Simple build system and CLI for AMX Mod X projects. ?? About This system will be useful for projects with multiple plugins and assets. Usi

Hedgehog Fog 11 Nov 15, 2022
This template is designed for compiling Rust libraries into WebAssembly and publishing the resulting package to NPM.

This template is designed for compiling Rust libraries into WebAssembly and publishing the resulting package to NPM.

Keith 2 Jul 5, 2022
This Photoshop script exports all top-level layers and groups to cropped PNG and JPEG files and creates a file usable in Tumult Hype 4 based on your Photoshop document.

Export To Hype (Photoshop Edition) This Photoshop script exports all top-level layers and groups to cropped PNG and JPEG files and creates a file usab

Max Ziebell 6 Nov 9, 2022
Google-Drive-Directory-Index | Combining the power of Cloudflare Workers and Google Drive API will allow you to index your Google Drive files on the browser.

?? Google-Drive-Directory-Index Combining the power of Cloudflare Workers and Google Drive will allow you to index your Google Drive files on the brow

Aicirou 127 Jan 2, 2023
Obsidian plugin that allows user to create a glossary of files, an index of files or both.

Obsidian Auto Glossary Auto Glossary is an Obsidian plugin to create a glossary, an index or a glossary with an index from the files you want. Feature

Ennio Italiano 29 Dec 30, 2022
In this project, I built a simple HTML list of To-Do tasks. This simple web page was built using Webpack, creating everything from a JavaScript index file that imported all the modules and assets

To Do List In this project, I built a simple HTML list of To-Do tasks. This simple web page was built using Webpack, creating everything from a JavaSc

Andrés Felipe Arroyave Naranjo 10 Mar 31, 2022
✂️ Find unused files, dependencies and exports in your TypeScript project

✂️ Knip Knip scans your JavaScript and TypeScript projects for unused files, dependencies and exports: things that can be removed! Less code means bet

Lars Kappert 673 Jan 1, 2023
Move files and directories to the trash

Move files and folders to the trash Works on macOS (10.12+), Linux, and Windows (8+). Note: The Linux implementation is not very good and not maintain

Sindre Sorhus 2.4k Dec 29, 2022
Is a collection of utils for the system, directories, deno and files informations :p

Is a collection of utils for the system, directories, deno and files informations :p

Dpm Land 2 Jul 22, 2022
A simple code that creates a string of random characters displayed in an html object, all saving in a json file.

I'm 17 Years Old Developer / Lead Developer. ?? I'm wroking on AdrenalinaRP, GrandRDM. ?? I’m currently learning JavaScript. ?? I’m looking to collabo

OFFVIXEN 2 Nov 17, 2022
This module exports all the commands that Redis supports

This module exports all the commands that Redis supports

ioredis 5 Mar 24, 2022
🤖 An action that fetches the list of malicious domains on Discord in different providers and creates/updates a JSON file with them from time to time.

Discord Guardian Action ??  This action fetches the list of malicious domains on Discord in different providers and creates/updates a JSON file with t

Dalton Menezes 7 Nov 30, 2022
Further split the React Native code based on Metro build to improve performance, providing `Dll` and `Dynamic Imports` features

React-Native Code Splitting Further split the React Native code based on Metro build to improve performance, providing Dll and Dynamic Imports feature

Wuba 126 Dec 29, 2022
Sheetzapper imports your account value accross Zapper.fi supported wallets and dapps into a Google Sheet

Overview Sheetzapper imports your account value accross Zapper.fi supported wallets and dapps into a Google Sheet. This allows you to chart your net w

null 4 Nov 27, 2022
A style export tool that live edits and exports code ready to copy / paste

Awesome Title Generator A style export tool that live edits and exports code ready to copy / paste. Features Edits text and live previews it CSS and R

Crhistian de Oliveira 19 Oct 7, 2022
Combine type and value imports using Typescript 4.5 type modifier syntax

type-import-codemod Combines your type and value imports together into a single statement, using Typescript 4.5's type modifier syntax. Before: import

Ian VanSchooten 4 Sep 29, 2022