Настройка этапов разработки с использованием gulp / package. json - PullRequest
0 голосов
/ 28 февраля 2020

ОК, поэтому я пробую новую настройку, чтобы дать мне более эффективный способ разработки моих сайтов.

На данный момент я могу думать только о 3 этапах: разработка, подготовка и сборка

Поскольку я использую gulp, я набираю gulp в Терминале, чтобы начать работу, а затем создаю свой сайт сборки.

Вместо того, чтобы запускать команду Gulp Я хотел бы использовать что-то вроде npm запустить разработку или npm запустить подготовку или npm запустить сборку

I понять, набрав Gulp , он автоматически ищет файл gulpfile. js. Как мне создать свои собственные файлы?

Я понимаю, что это как-то связано со скриптами в пакете. json файл, но я не могу понять, как.

Вот что у меня так далеко :

{
  "name": "Name",
  "version": "1.0.0",
  "description": "Description",
  "main": "index.html",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "development": "node builds/development.js",
    "staging": "node builds/staging.js",
    "build": "node builds/build.js"
  },
  "author": "Author name here",
  "license": "ISC",
  "devDependencies": {
    "gulp": "^4.0.2",
  },
  "dependencies": {
  }
}

Теперь, когда я наберу '1039 * run staging' (точную копию gulpfile. js), я ожидаю, что он начнется так же, как если бы я набрал Gulp

ОБНОВЛЕНИЕ: Вот мой глоток

// --------------------------------------------
// Gulp Loader
// --------------------------------------------
// Stop having to put gulp. infront of the following
const {
  src,
  dest,
  task,
  watch,
  series,
  parallel
} = require("gulp");

// --------------------------------------------
// Dependencies
// --------------------------------------------

// HTML plugins
var htmlmin = require("gulp-htmlmin");

// CSS / SASS plugins
var sass = require('gulp-sass');
var cleanCSS = require('gulp-clean-css');

// Images plugins
// let imagemin = require("gulp-imagemin");
var embedSvg = require("gulp-embed-svg");

// Browser plugins
var browserSync = require('browser-sync').create();

// Utility plugins
var plumber = require("gulp-plumber");
var rename = require("gulp-rename");
var cache = require('gulp-cache');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var shell = require('shelljs');
var uglify = require('gulp-uglify');
var del = require("del");
var inject = require('gulp-inject');
var shell = require('shelljs');
var noop = require('gulp-noop');
// --------------------------------------------
// Get Home Folder location
// --------------------------------------------
//Displays Users/User
const homedir = require("os").homedir();
// Needed for next part
var path = require("path");
//Displays Users/User/Documents/Clients/clientname/Projects (This is where I create my client folders)
var pathDir = require("path").resolve(__dirname, "../../");
var pathSrc = require("path").resolve(__dirname, "../../../");
//Display the name of the Clients folder name
var parentFld = path
  .dirname(pathDir)
  .split(path.sep)
  .pop();
var parentDir = path.basename(path.dirname(pathDir));
parentDir = parentFld.replace(/[^\w]/g, "");
parentDir = parentFld.replace(/[^\w]/g, "").toLowerCase();


// BrowserSync
function server(done) {
  browserSync.init({
    proxy: "http://" + parentDir + ".test",
    host: parentDir + ".test",
    open: "external",
    notify: false
  });
  done();
}

// function watcher() {
// Serve files from the root of this project
//  browserSync.init({
//    proxy: "https://" + parentdir + ".test",
// //   host: parentdir + ".test",
// open: "external",
//   https: {
//     key: homedir + "/.config/valet/Certificates/" + parentdir + ".test.key",
//    cert: homedir + "/.config/valet/Certificates/" + parentdir + ".test.crt"
// },
// browser: "Google Chrome Canary",
// notify: false
// });

// --------------------------------------------
// Paths
// --------------------------------------------
var paths = {
  htaccess: {
    src: './source/.htaccess',
    dest: './development/.htaccess',
  },
  html: {
    src: './source/*.html',
    prt: './source/partials/*.html',
    dest: './development/'
  },
  styles: {
    src: 'source/styles/*.css',
    dest: 'development/styles/'
  },
  scripts: {
    src: 'source/scripts/*.js',
    dest: 'development/scripts'
  }
}

// --------------------------------------------
// Tasks
// --------------------------------------------


//Basic task with a log - SHOW $homedir
function home(cb) {
  console.log(fontBld);
  cb()
}
task('default', function () {
  console.log('Hello World!');
});

//Basic task with a log
function ssg(cb) {
  console.log(parentDir);
  cb()
}

// CONSOLE LOG
function console_log(cb) {
  console.log(parentDir);
  cb()
}

function valet_link(cb) {
  shell.mkdir(['development']);
  shell.cd(['./development']);
  if (shell.exec('sudo valet link' + ' ' + parentDir).code !== 0) {
    shell.echo('Error: Git commit failed');
    shell.exit(1);
  }
  shell.cd(['..']);
  cb()
}

// CLEAN
function clean(cb) {
  del.sync(paths.html.dest, {
    force: true
  });
  cb()
}

// HT ACCESS
function htaccess() {
  return src(paths.htaccess.src)
    .pipe(dest(paths.htaccess.dest));
}

// HTML
function html() {
  var injectPartials = src(paths.html.prt, {
    relative: true
  });
  var injectStyles = src([paths.styles.src], {
    relative: true
  });
  var injectScripts = src(paths.scripts.src, {
    relative: true
  });
  return src(paths.html.src)
    .pipe(inject(injectPartials, {
      starttag: '<!-- inject:header:{{ext}} -->',
      transform: function (filePath, file) {
        // return file contents as string
        return file.contents.toString('utf8')
      }
    }))
    .pipe(inject(injectStyles, {
      addRootSlash: false,
      ignorePath: '/source/'
    }))
    .pipe(inject(injectScripts, {
      addRootSlash: false,
      ignorePath: '/source/'
    }))
    .pipe(
      embedSvg({
        root: "./source/images/",
        selectors: ".inline-svg"
      })
    )
    .pipe(dest(paths.html.dest));
}

// CSS
function css() {
  return src(paths.styles.src)

    .pipe(sass({
      outputStyle: 'compressed'
    }))
    .pipe(plumber())
    .pipe(dest(paths.styles.dest))
}

// JS
function js() {
  return src(paths.scripts.src)

    .pipe(
      rename({
        basename: "main",
        suffix: ".min"
      })
    )
    .pipe(plumber())
    .pipe(uglify())
    .pipe(dest(paths.scripts.dest));
}

// IMAGES
function img(done) {
  src(imageSrc + "*")
    .pipe(imagemin())
    .pipe(dest(imageDest));
  done();
}

// FONTS
function fonts(done) {
  src(fontSrc + "*").pipe(dest(fontDest));
  done();
}

function clearCache(done) {
  cache.clearAll();
  done();
}
// --------------------------------------------
// Watch
// --------------------------------------------
function watcher() {
  watch(paths.styles.src).on('change', series(css, browserSync.reload));
  watch(paths.scripts.src).on('change', series(js, browserSync.reload));
  watch(paths.htaccess.src).on('change', series(htaccess, browserSync.reload));
  watch(paths.html.src).on('change', series(html, browserSync.reload));
}

// --------------------------------------------
// Compile
// --------------------------------------------
exports.test = series(clean, html)
exports.log = console_log
exports.valet = valet_link
// --------------------------------------------
// Build
// --------------------------------------------
// CONSOLE LOG
function build_log(cb) {
  console.log("Please either use 'npm run production' or 'npm run development'");
  cb()
}

var compile = series(clean, valet_link, series(html, css, js));

task('default', series(compile, parallel(server, watcher)));

1 Ответ

0 голосов
/ 11 марта 2020

Вам не нужно создавать несколько файлов gulp, вы можете просто иметь один файл gulp. js и просто вызывать файл gulp в своем пакете. json так, как вы уже делаете это так:

"scripts": {
    "gulp": "gulp",
    "test": "echo \"Error: no test specified\" && exit 1"
},

Чем в файле gulp вы просто создаете свой экспорт следующим образом:

exports.development = function devFunction(){ ... };
exports.staging = function stagingFunction(){ ... };
exports.build = function buildFunction(){ ... };

Если бы вы выполнили каждую задачу, вы бы назвали «gulp task » следующим образом:

gulp development
...