** Chuẩn bị
1. Cài đặt NodeJS: https://nodejs.org/en/download/
2. Kiểm tra version của NodeJS và NPM, sau đó tạo project
node -v
npm -v
npm init -y
1. Cài đặt ./package.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
{ "name": "@duycode/create-fakeapi", "version": "1.0.0", "description": "", "main": "index.js", "bin": { "@duycode/create-fakeapi": "bin/create-fakeapi", "create-fakeapi": "bin/create-fakeapi" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" } |
Giải thích:
-- Bắt buộc: "name": tên project phải bắt đầu có chữ "create-*"
-- 2 lệnh "bin" tương ứng
+ "create-fakeapi": câu lệnh CLI tại local (tại chính máy tính của mình)
+ @duycode/create-fakeapi ==> sau này update lên npmjs thì có 2 cách chạy dòng này:
npm init @duycode/fakeapi
npx @duycode/create-fakeapi
-- bin/create-fakeapi: chính là nơi thực thi 2 dòng lệnh đó
2. Cài đặt BIN
-- Tạo file: ./bin/create-fakeapi (không có đuôi file, nhưng có cú pháp viết của js)
-- Bắt buộc ở đầu file: "#!/usr/bin/env node"
1 2 |
#!/usr/bin/env node console.log('Congratulation ! You are Ready'); |
3. Đăng ký sử dụng CLI
-- Tại thư mục project, chạy lệnh sau:
npm link
-- CLI đã được đăng ký tại 2 thư mục sau:
C:\Users\duyk3\AppData\Roaming\npm
C:\Users\duyk3\AppData\Roaming\npm\node_modules
4. Khởi chạy lần đầu
Dùng CMD tại chính folder của project
create-fakeapi
-> Kết quả: 'Congratulation ! You are Ready'
5. Sử dụng Demo
-- Tại file: ./bin/create-fakeapi
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#!/usr/bin/env node const { execSync } = require('child_process') const repoName = process.argv[2] || "./" const gitURL = 'https://github.com/duyk30b/duyk30b.github.io.git'; const gitCloneCommand = `git clone ${gitURL} ${repoName}`; const installCommand = `cd ${repoName} && npm install`; try { execSync(gitCloneCommand); execSync(installCommand); } catch (error) { process.exit(-1); } console.log('Congratulation ! You are Ready :D'); |
-- Sử dụng CLI
create-fakeapi newfolder
--> kết quả: 1 folder mới đã được tạo ra từ clone github, sau đó đã tự install hoàn toàn mọi thứ :D, hay chưa
6. Đưa lên npmjs
-- Thêm vào package.json
1 2 3 |
"publishConfig": { "access": "public" }, |
-- Phblish thôi (nhớ phải login trước khi publish)
npm publish
7. Sử dụng nâng cao hơn
Khi cần nhiều options hơn, cần sử dụng thêm những thư viện sau:
1. arg : phân tích biến đầu vào, như -v, --y, -g, --install ==> tạo options hợp lý để xử lý logic
2. inquirer: Tạo bộ câu hỏi khi bắt đầu cài
3. ncp : copy file
4. execa : tạo các lệnh thực thi ngoài: như: "git init", "git clone .."
5. pkg-install: install các thư viện, dùng npm hoặc yarn
6. listr: quản lý nhiệm vụ và hiển thị đẹp hơn các quá trình cài đặt ncp, execa, pkg-install
7. chalk : console.log đẹp hơn