- Installing Gulp on macOS BIg Sur – Intro guide to Gulp
- Install Gulp globally
- Install Gulp locally – package.json
- Permissions Issue with package.json file
- Save Dependencies
- gulpfile.js
- Gulp command not found after install
- 12 Answers 12
- How to: change permissions in order to run npm without sudo
- Step 1: Find out where npm’s default directory is.
- Step 2: Proceed, based on the output of that command:
- Step 3: Change npm’s default directory:
- Step 4: Update the permissions on npm’s default directory:
- WEB-Верстка
- SASS — CSS препроцессор (Часть 2-я) — Gulp
- Теперь переходим к установке Gulp
- Далее выполним инициализацию Gulp
- УСТАНОВИЛИ SASS!
- УСТАНОВИЛИ SASS для Sublime Text!
- Инициализация Gulp
- package.json
Installing Gulp on macOS BIg Sur – Intro guide to Gulp
Installing Gulp on macOS Big Sur, macOS Sierra and earlier OS versions requires Nodejs and npm (Node Package Manager), so get that installed first following the linked guide.
Gulp is an easier and slightly more modern javascript task runner than its sibling Grunt, which helps you automate numerous tasks in your workflow. You need to install Gulp both globally and locally in your project.
Install Gulp globally
Launch your Terminal app and install gulp globally.
macOS users need to use sudo to install gulp across all accounts.
Install Gulp locally – package.json
For a local project you need to set up a package.json file first to configure your Node/npm packages and dependencies. From the Terminal, change directory into your project folder and issue the command npm init to create the package.json file.
npm init helps create your package.json file, here you just follow the prompts:
So I have only added values for name, version, description and author and left the rest blank say OK and the file will be written out to your project folder – then you can then also remove some of the outputted blank fields in a text editor – so now giving us this…
Note the last comma is removed.
Permissions Issue with package.json file
You may get a permissions issue with the package.json file..
Just run the command below to fix – change
Save Dependencies
Once we have our json file in place we can install the local gulp package via the command line in our project which will write to our package.json file, so in the command line make sure you are in your project directory and install gulp like so
Now our package.json file will be like so…
To add further plugins, for instance lets install the live browser reloading tool BrowserSync. To install locally to your project use the following syntax in your Terminal commands…
The parameter –save-dev will save the package as a dependency to the project and write itself to the package.json file. Which will now be like so:
gulpfile.js
Our last configuration file required is a gulpfile.js which is what tells gulp what to do – the gulpfile.js has variables and tasks and at least has the variable for gulp itself – so create this file in the root of the project and add…
But this is not going to do much on it’s own, so with browsersync plugin installed I want to create a task that allows me to see a web project open in the browser and live reload when I change the CSS file, so now my gulpfile.js will look like this…
And I run this gulp task from the command line whilst in my project by using
Источник
Gulp command not found after install
I installed gulp(globally) and it looks like it worked because it ran this code:
But when I type gulp it says -bash: gulp: command not found
Any idea what’s going on?
12 Answers 12
Turns out that npm was installed in the wrong directory so I had to change the “npm config prefix” by running this code:
Then I reinstalled gulp globally (with the -g param) and it worked properly.
Not sure why the question was down-voted, but I had the same issue and following the blog post recommended solve the issue. One thing I should add is that in my case, once I ran:
I confirmed the npm root -g was pointing to /usr/local/lib/node_modules/npm , but in order to install gulp in /usr/local/lib/node_modules , I had to use sudo :
sudo npm install gulp -g
If you’re using tcsh (which is my default shell on Mac OS X), you probably just need to type rehash into the shell just after the install completes:
followed immediately by:
Otherwise, if this is your very first time installing gulp , your shell may not recognize that there’s a new executable installed — so you either need to start a new shell, or type rehash in the current shell.
(This is basically a one-time thing for each command you install globally.)
I realize that this is an old thread, but for Future-Me, and posterity, I figured I should add my two-cents around the «running npm as sudo» discussion. Disclaimer: I do not use Windows. These steps have only been proven on non-windows machines, both virtual and physical.
You can avoid the need to use sudo by changing the permission to npm’s default directory.
How to: change permissions in order to run npm without sudo
Step 1: Find out where npm’s default directory is.
- To do this, open your terminal and run:
npm config get prefix
Step 2: Proceed, based on the output of that command:
- Scenario One: npm’s default directory is /usr/local
For most users, your output will show that npm’s default directory is /usr/local, in which case you can skip to step 4 to update the permissions for the directory. - Scenario Two: npm’s default directory is /usr or /Users/YOURUSERNAME/node_modules or /Something/Else/FishyLooking
If you find that npm’s default directory is not /usr/local, but is instead something you can’t explain or looks fishy, you should go to step 3 to change the default directory for npm, or you risk messing up your permissions on a much larger scale.
Step 3: Change npm’s default directory:
- There are a couple of ways to go about this, including creating a directory specifically for global installations and then adding that directory to your $PATH, but since /usr/local is probably already in your path, I think it’s simpler to just change npm’s default directory to that. Like so: npm config set prefix /usr/local
- For more info on the other approaches I mentioned, see the npm docs here.
Step 4: Update the permissions on npm’s default directory:
- Once you’ve verified that npm’s default directory is in a sensible location, you can update the permissions on it using the command:
sudo chown -R $(whoami) $(npm config get prefix)/
Now you should be able to run npm without sudo . Note: You may need to restart your terminal in order for these changes to take effect.
Источник
WEB-Верстка
SASS — CSS препроцессор (Часть 2-я) — Gulp
И так: NODE.JS — УСТАНОВЛЕН!
Теперь переходим к установке Gulp
В пути к папке проекта — НЕ ДОЛЖНО БЫТЬ РУССКОЯЗЫЧНЫХ ПАПОК!
Откроем терминал
в папке нашего рабочего проекта:
Далее пишим команду:
Идет установка Gulp:
А для пользователей MAC прийдется выполнить команду с правами СУПЕР-ПОЛЬЗОВАТЕЛЯ:
И ТАК, УСТАНОВКА Gulp на MAC:
Ввести ниже указанную команду: sudo npm i gulp -g
Возможно придется поставить курсор в ключик)
И с 1-раза может не получиться, но со 2-й попытки, териминал «принял» админский пароль:
Установка Gulp на MAC — ЗАВЕРШЕНА!
Далее выполним инициализацию Gulp
Набираем ( уже БЕЗ пароля и без sudo )
myproject> npm init
И далее, нам нужно ответить на некоторые вопросы связанные с проектом.
Далее, собственно установим Gulp
Но бывает случается такой момент когда появляется такое сообщение — тогда делаем следующее:
ПОЛУЧИЛИ СООБЩЕНИЕ (Сразу с подсказской)
Копируем эту подсказку и вставляем как команду: (указав свой логин учетной записи от MAC)
Пошла установка Gulp
Установка ЗАВЕРШЕНА!
И чтобы открывать Terminal — из любой папки делаем следующие настройки:
И таким образом уже открываем Terminal:
Можно пройти в папку и посмотреть как выглядит Gulp
А здесь рассмотрим, как быстро создавать текстовые файлы в паке на MAC.
Качаем программку iMakerTxtFile
Например здесь:
https://sageleo.com/wp-content/uploads/2017/05/iMakerTxtFile.zip
Распаковываем в папке и далее один ньюанс:
Для того чтобы перенести Значек программы ( иконку ) на панель папки — необходимо Разрешить использование сторонней программы в настройках самого MAC:
Разрешим нужную программу:
И затем, перетащим иконку программы на панель папки удерживая (Comand) Cmd
Теперь для создания текстового файла — кликнуть на иконке (на панели папки) и получим окно создания файла:
Готово! Работает! Файлы создаются!
Далее возвращаемся к инструкции для Windows.
Создадим файл gulpfile.js
в папке myproject
И наберем в нем код:
var gulp = require ( ‘gulp’ ); |
gulp. task (‘ mytask ‘, function () < |
console . log (‘ Сообщение ура! ‘) |
> ); |
Затем перейдем в Terminal
и выполним наш таск: mytast
НЕ ЗАБЫВАЕМ УСТАНОВИТЬ Gulp sass в Terminal MAC.
Командой: npm i gulp-sass —save-dev
УСТАНОВИЛИ SASS!
Не забываем также установить SASS для Sublime Text
УСТАНОВИЛИ SASS для Sublime Text!
Проверим работу сниппета для Sass в Sublime Text: — Проверили Работает!
sass-css-part-3
Инициализация Gulp
Для того что бы начать проект — нам нужно его инициализировать:
Эта команда позволяет инициализировать и создать базовый стартовый файл манифеста для нашего проекта.
Далее нужно ответить на несколько вопросов:
извините, имя больше не может содержать заглавные буквы
Поэтому укажем имя только низкими буквами :
Далее:
Далее просто:
Тоже просто:
У нас нет Репозитория — поэтому тоже:
Тоже просто:
Автора можем указать:
И жмем:
Оставляем и :
Далее если все правельно — пишим «YES»
и жмем :
И должен появиться файлик:
package.json
Давайте его откроем:
Дальше идем)
Файл package.json — является манифестом проекта.
Кроме того он хранит информацию об используемых пакетах в нашем проекте.
Например если устанавливать Gulp c другим пакетом —
gulp save dev — то эта версия, автоматически добавиться в наш файлик package.json
— Это позволяет быстро разворачивать проект, с учетом уже имеющегося package.json
и устанавливать необходимые модули с зависимостями, которые прописываются в package.json новых проектов.
Далее установим наш проект Gulp!
Терминал — не закрывали — в нем и продолжаем:
Источник