{cross plataforma}

Criando npm scripts

William Grasel

Cross Plataforma?

entendendo o problema...

// package.json
...
"scripts": {
  "clean": "rm -rf ./build",
  "build": "npm run clean && tsc",
  "lint": "eslint src/**/*.ts",
  "deploy": "./deploy.sh"
},
...
#

Consegue encontrar os problemas?

Nem todo mundo usa Bash

ou pelo menos a mesma versão dele...

O projeto não deveria nos obrigar a ter um setup específico

Não precisa ser complicado!

Resolvendo problemas comuns

import { glob } from 'glob'

// all js files, but don't look in node_modules
const jsfiles = await glob('**/*.js', {
  ignore: 'node_modules/**'
});

// pass in a signal to cancel the glob walk
const stopAfter100ms = await glob('**/*.css', {
  signal: AbortSignal.timeout(100),
});
#

Obtendo arquivos:

Muitos projetos já

usan node-glob

por padrão

// package.json
...
"scripts": {
  "clean": "rm -rf ./build",
  "build": "npm run clean && tsc",
  "lint": "eslint  src/**/*.ts ",
  "deploy": "./deploy.sh"
},
...
#

Uma mudança simples:

// package.json
...
"scripts": {
  "clean": "rm -rf ./build",
  "build": "npm run clean && tsc",
  "lint": "eslint 'src/**/*.ts'",
  "deploy": "./deploy.sh"
},
...

Use aspas em todas as strings com * em seus scripts!

$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo
#

shx to rule then all!

JavaScript + Bash = ❤️

var shell = require('shelljs');

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}

// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');

// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(file => {
  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');

// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
  shell.echo('Error: Git commit failed');
  shell.exit(1);
}
# PRESENTING CODE
// package.json
...
"scripts": {
  "clean": "shx rm -rf ./build",
  "build": "npm run clean && tsc",
  "lint": "eslint 'src/**/*.ts'",
  "deploy": "node ./deploy.js"
},
...
#

Use shx por padrão:

$ npm-run-all clean lint build
$ npm-run-all clean lint --parallel watch:html watch:js
$ npm-run-all --parallel 'watch:**'

# shortcuts
$ run-s 'build:**'
$ run-p 'build:**'
#

run then all!

"scripts": {
  "start": "run-s build 'start-server -- --port {1}' --"
}

$ npm start 8080
#

Passando argumentos:

// package.json
...
"scripts": {
  "clean": "shx rm -rf ./build",
  "ts-build": "tsc ./tsconfig.json",
  "build": "npm-run-all clean ts-build",
  "lint": "eslint 'src/**/*.ts'",
  "deploy": "node ./deploy.js"
},
...
#

Finalmente

// package.json
...
"scripts": {
  "build:1:clean": "shx rm -rf ./build",
  "build:2:ts": "tsc ./tsconfig.json",
  "build": "nun-s 'build:**'",
  "lint": "eslint 'src/**/*.ts'",
  "deploy": "node ./deploy.js"
},
...
#

Finalmente

Bonus Time!

Melhor experiência

que já tive com

JS + Bash

Mas nem tudo funciona perfeitamente no Windows com Powershell

Uma das melhores

abstrações de complexidade

de build e gerenciamento

de repositórios

Usando o Nx eu praticamente nem preciso lembrar de todas as outras dicas que dei anteriormente

Por hoje é só!

Obrigado!

Criando npm scripts cross plataforma

By William Grasel

Criando npm scripts cross plataforma

Node.js e npm são projetos cross plataforma, com suporte para múltiplos Sistemas Operacionais, porém não é incomum pegar em projetos onde os scripts de build, teste e etc funcionam apenas no Linux ou no Mac, forçando os desenvolvedores a montarem setups mais complicados que por vezes não é onde eles se sentem mais confortáveis. E se eu te falar que não é complicado fazer esses scripts serem não apenas multi plataforma, como muito mais legíveis e fáceis de dar manutenção?

  • 148