Как создать собственный модуль node_module для загрузки в виде папки, такой как реакция / начальное приложение, а не в node_module - PullRequest
0 голосов
/ 18 апреля 2019

У меня есть свой собственный узел_модуля https://www.npmjs.com/package/@aakashdeveloper/create-node-app

Он создан для запуска нового приложения узла. Проблема с этим модулем узла - когда мы его устанавливаем, он загружается как любой другой пакет в папку node_module и добавляется в package.json.

Мое требование - загружать как начальную папку. Может ли кто-нибудь помочь.

Проблема в основном связана с package.json, где я добавил «bin» и «file», я действительно не уверен.

{
  "name": "@aakashdeveloper/create-node-app",
  "version": "1.0.33",
  "description": "The Seed will help you build node app with es6 very quick",
  "main": "index.js",
  "scripts": {
    "start": "node start.js",
    "dev": "nodemon start.js",
    "test": "mocha --timeout 10000",
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Aakashdeveloper/create-node-app"
  },
  "keywords": [
    "Node",
  ],
  "author": "aakashdeveloper",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/Aakashdeveloper/create-node-app/issues"
  },
  "homepage": "https://github.com/Aakashdeveloper/create-node-app#readme",
  "dependencies": {
    "@babel/core": "^7.4.3",
  }
}

Мне нужно загрузить как Creata-реагировать на приложение.

1 Ответ

0 голосов
/ 18 апреля 2019

Я думаю, вы неправильно поняли процесс create-react-app или аналогичные модули.Вам необходимо установить свой модуль как глобальный модуль и предоставить cli, с помощью которого вы можете создавать файлы проекта в заданном каталоге.Вы можете использовать yargs для обработки команд и аргументов, а затем для создания необходимых файлов в указанном каталоге.Ниже приведен пример кода (без проверки), в котором вы можете получить основную идею.

#!/usr/bin/env node

const path = require("path");
const fs = require("fs");

//  the dir where the base files are stored 
//  in case you use the copyFiles method
const baseFilesDir = path.join(__dirname, "base");

// get the dir from the user.
const dir = getDirFromArg(process.argv[2]);

if(!dir){
    console.log('Please specify a directory to create project');
}

//  create node app in the given directory

createNodeAppInDir(dir);

/****** HELPERS *****/

function getDirFromArg(arg){
    switch(arg){
        case '.':
        case '..':
            return path.normalize(__dirname, arg);
        default:
            return path.normalize(arg); 
    }
}

async function createNodeAppInDir(dir){

    const dirExists = await checkDir(dir);

    if(!dirExists){
        try{
            await createDir(dir);
        }
        catch(e){
            //  display the error to user and break the operation
            //  may be there is a permission issue
            console.error(e);
            return false;
        }
    }

    //   now copy base files to the directory 
    //   or create new files in there, your choice 
    //   copying would be my preference though

    try{
        await copyBaseFiles(dir);
    }
    catch(e){
        console.error(e);
        return false;
    }
}

//  check if the directory exists
const checkDir = (dir) => {
    return new Promise((resolve, reject) => {
        fs.access(dir, (err) => {
            if(err){
                //  directory doesn't exist
                return resolve(false);
            }

            //  direcotry exists
            return resolve(true);
        });
    });
}

//  create directory
const createDir = (dir) => {
        return new Promise((resolve, reject) => {
        fs.mkdir(dir, { recursive: true }, (err) => {
            if(err){
                //  unable to create directory
                return reject(err);
            }

            //  direcotry successfully created
            return resolve(true);
        });
    });
}

const copyBaseFiles = (dir) => {
    //  copy the contents of the src dir to the destination dir
    copyDir(baseFilesDir, dir);
}

//  credit:: https://gist.github.com/tkihira/3014700

var mkdir = function(dir) {
    // making directory without exception if exists
    try {
        fs.mkdirSync(dir, 0755);
    } catch(e) {
        if(e.code != "EEXIST") {
            throw e;
        }
    }
};

var rmdir = function(dir) {
    if (path.existsSync(dir)) {
        var list = fs.readdirSync(dir);
        for(var i = 0; i < list.length; i++) {
            var filename = path.join(dir, list[i]);
            var stat = fs.statSync(filename);

            if(filename == "." || filename == "..") {
                // pass these files
            } else if(stat.isDirectory()) {
                // rmdir recursively
                rmdir(filename);
            } else {
                // rm fiilename
                fs.unlinkSync(filename);
            }
        }
        fs.rmdirSync(dir);
    } else {
        console.warn("warn: " + dir + " not exists");
    }
};

var copyDir = function(src, dest) {
    mkdir(dest);
    var files = fs.readdirSync(src);
    for(var i = 0; i < files.length; i++) {
        var current = fs.lstatSync(path.join(src, files[i]));
        if(current.isDirectory()) {
            copyDir(path.join(src, files[i]), path.join(dest, files[i]));
        } else if(current.isSymbolicLink()) {
            var symlink = fs.readlinkSync(path.join(src, files[i]));
            fs.symlinkSync(symlink, path.join(dest, files[i]));
        } else {
            copy(path.join(src, files[i]), path.join(dest, files[i]));
        }
    }
};

var copy = function(src, dest) {
    var oldFile = fs.createReadStream(src);
    var newFile = fs.createWriteStream(dest);
    oldFile.pipe(newFile);
};

...