1-я попытка пакетного файла — проблемы с асинхронными командами

Я пытаюсь написать свой первый пакетный файл, который создает приложение React (с помощью диспетчера пакетов узлов), вложенное в проект SilverStripe, и переименовывает файлы сборки js и css и перемещает файлы сборки мультимедиа в новый каталог в проекте SilverStripe. (чтобы их мог получить виртуальный хост, настроенный так, чтобы он указывал на проект SilverStripe).

Чтобы запустить скрипт в cmd, я использую следующее имя скрипта с двумя аргументами:

updateReactInSS "C:\wamp64\www\example5" "C:\wamp64\www\example5\app\moe-card-app"

Сценарий успешно выполняет сборку npm run, но после этого не продолжается. Мои догадки:

  • Что-то асинхронное может происходить? Я добавил тайм-аут для этого, но может иметь неправильный синтаксис. Следующая строка никогда не выполняется: echo "ТАЙМ-АУТ завершен. Скрипт продолжается..."
  • Может быть, у меня неправильный синтаксис, чтобы попасть в нужные каталоги?

Ниже приведен полный сценарий:

Rem ============================================================================================
Rem This batch script builds a React Application inside SilverStripe and
Rem moves media files if they exist to the public directory of the SilverStripe project.
Rem command line argument 1 = full path to the nested SilverStripe project folder
Rem command line argument 2 = full path to the nested React application
Rem It relies on node package manager and composer being installed.
Rem The result works with a virtual host configured to point at the SilverStripe project folder.
Rem =============================================================================================
@echo off
Rem Checking argument 1 entered correctly.
if "%~1"= = "" (
echo You forgot to specify the full path to the SilverStripe project folder:
echo argument 1 = ?
goto finished
) else (
echo argument 1 = The path to the SilverStripe project folder is:
echo %1
)
Rem Checking argument 2 entered correctly.
if "%~2"= = "" (
echo You forgot to specify the full path to the nested React application:
echo argument 2 = ?
goto finished
) else (
echo argument 2 = The path to the nested React application is:
echo %2
)
Rem Going to React application path. NOTE: could also add condition to check npm install if 1st time run
cd %2
cd
Rem Delete build directory if it exists. Using node package manager to build the React application.
if exist build\ del build /s /e
npm run build
Rem Adding time for npm run build to finish before continuing
TIMEOUT /T 20
echo TIMEOUT finished. Script continuing...
Rem Rename main.hashcode.js to main.bundle.js so consistent with requirements in related SS page controller.
cd %2\build\static\js
cd
rename main.*.js "main.bundle.js"
Rem Rename main.hashcode.css to main.bundle.css so consistent with requirements in related SS page controller.
cd %2\build\static\css
cd
rename main.*.css "main.bundle.css"
Rem Going to to SilverStripe project root to run composer vendor-expose command creating sym-links if not there.
cd %1
composer vendor-expose
Rem Copying media build files if media directory exists in React build files to the public folder in SilverStripe. project.
if exist %2\build\static\media (
MD /public\static\media
xcopy %2\build\static\media %1/public\static\media /s /e
) else (
goto finished
)
if errorlevel 4 goto lowmemory
if errorlevel 2 goto abort
if errorlevel 0 goto exit
:lowmemory
echo Insufficient memory to copy files or
echo invalid drive or command-line syntax.
goto exit
:abort
echo You pressed CTRL+C to end the copy operation.
goto exit
:finished
echo The programme updateReactInSS has completed.
:exit

Вот связанный с этим вопрос, который я задал по этому поводу в StackOverFlow, с более подробной информацией о том, чего я пытаюсь достичь. Если вы ответите на этот вопрос, вы также ответите, что один = 2 зайца одним выстрелом!!!

Лучшее, что я могу предложить на данный момент, это то, что вы узнаете, как работает каждая команда. Для этого вы можете получить доступ к справочной информации для каждого из них, введя имя команды, а затем ее параметр справки, /? в командной строке. Кроме того, вы должны использовать Rem для примечаний, а не искаженные ярлыки, ::. Чтобы проверить наличие пустых аргументов, вы должны использовать If "%~1" == "", а для проверки существования каталога, а не файла, вы должны использовать обратную косую черту в конце, if exist build\ . Я бы также посоветовал вам не заключать строки echo в двойные кавычки, например. If Exist "build\" и CD "%~1".

Compo 23.05.2019 00:47

Большое спасибо! Я внесу эти изменения в сценарий и отредактирую этот вопрос.

Bevan Shaw 23.05.2019 03:12
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Массив зависимостей в React
Массив зависимостей в React
Все о массиве Dependency и его связи с useEffect.
0
2
71
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Обходной путь для этой проблемы заключался в том, чтобы разбить исходный один скрипт на 2 скрипта, которые можно запускать в командной строке. Этот сплит необходимо было продолжить после того, как npm run build финиширует, и если composer vendor-expose нужно запустить и закончить. Это потому, что мой сценарий автоматически закрывается, когда они заканчиваются. Ниже приведены два скрипта с аргументами:

updateReactInSS_1 "C:\wamp64\www\silverstripeProject" "C:\wamp64\www\silverstripeProject\app\ReactApp"

Rem =======updateReactInSS_1=============
Rem updateReactInSS_1 is part 1 of 2 that updates a React Application nested inside a SilverStripe project.
Rem It deletes an existing React application build directory and rebuilds it with npm.
Rem Dependencies are node package manager (npm) and Composer installed globally by editing the
Rem environment variable path on your machine so they can be run from the command line (cmd).
Rem You also need a virtual host configured to point at your-SilverStripe-project folder.
Rem Argument 1 = full path to the nested SilverStripe project folder
Rem Argument 2 = full path to the nested React application
Rem updateReactInSS_1 file is located at Argument 2.
Rem updateReactInSS_2 file is located at Argument 2. It renames the "hash" js and css build files to "bundle"
Rem then copies and moves existing media build media files to the public directory of the SilverStripe project.
Rem Note: If "composer vendor-expose" runs then updateReactInSS_2 needs to be run again to complete the script.
Rem =======START===========
@echo off
Rem Checking argument 1 entered correctly.
if "%~1"= = "" (
echo You forgot to specify the full path to the SilverStripe project folder:
echo argument 1 = ?
goto exit
) else (
echo argument 1 = %1 (path to the SilverStripe project folder)
)
Rem Checking argument 2 entered correctly.
if "%~2"= = "" (
echo You forgot to specify the full path to the nested React application:
echo argument 2 = ?
goto exit
) else (
echo argument 2 = %2 (path to the nested React application)
)
Rem Going to React application path (NOTE could also add condition to check npm install if 1st time run)
cd %2
Rem Deletes the React application build directory if it exists and then use node package manager to build the React application.
if exist build\ del build /s /e
npm run build
:exit

updateReactInSS_2 "C:\wamp64\www\silverstripeProject" "C:\wamp64\www\silverstripeProject\app\ReactApp"

Rem updateReactInSS_2 is part 2 of 2.
Rem Argument 1 = full path to the nested SilverStripe project folder
Rem Argument 2 = full path to the nested React application
Rem updateReactInSS_2 file is located at Argument 2 (where updateReactInSS_1 is forced to end by npm run build).
Rem It renames the "hash" js and css build files to "bundle" and copies and moves
Rem existing build media files to the public directory of the SilverStripe project.
Rem Note: If updateReactInSS_2 is forced to end by composer vendor-expose command at Argument 1,
Rem you need to cd to Argument 2 to run updateReactInSS_2 again to complete the script. 
Rem If symlinks have already been created by Composer, the command composer vendor-expose is
Rem skipped so updateReactInSS_2 only needs to be run once from the command line. 
Rem =======START=======
@echo off
Rem Checking argument 1 entered correctly.
if "%~1"= = "" (
echo You forgot to specify the full path to the SilverStripe project folder:
echo argument 1 = ?
goto finished
) else (
echo argument 1 = %1 (path to the SilverStripe project folder)
)
Rem Checking argument 2 entered correctly.
if "%~2"= = "" (
echo You forgot to specify the full path to the nested React application:
echo argument 2 = ?
goto finished
) else (
echo argument 2 = %2 (path to the nested React application)
)
Rem Rename main.hashcode.js to main.bundle.js so consistent with requirements in related SS page controller.
cd %2\build\static\js
rename main.*.js "main.bundle.js"
Rem Rename main.hashcode.css to main.bundle.css so consistent with requirements in related SS page controller.
cd %2\build\static\css
rename main.*.css "main.bundle.css"
Rem checking if composer vendor-expose needs to run to create symlinking.
cd %1/public\resources
if not exist app\moe-card-app\build\ (
echo Please cd to %2 and run updateReactInSS_2 again to complete script commands.
cd %1
composer vendor-expose
)
Rem Go to public folder of SilverStripe project if no static\media directory exists, make it.
cd %1/public
if not exist static\media\ (
MD 1%/public\static\media
)
Rem Copying media build files if media directory exists in React build files to the public folder in SilverStripe. project.
if exist %2\build\static\media\ (
xcopy %2\build\static\media %1/public\static\media /s /e
) else (
echo No media directory to copy in react build\static\
goto exit
)
if errorlevel 4 goto lowmemory
if errorlevel 2 goto abort
if errorlevel 0 (
cd %2
goto finished
)
:lowmemory
echo Insufficient memory to copy files or
echo invalid drive or command-line syntax.
goto exit
:abort
echo You pressed CTRL+C to end the copy operation.
goto exit
:finished
echo updateReactInSS_2 COMPLETED
:exit

Пожалуйста, прокомментируйте с лучшими дизайнерскими решениями. Можно ли их объединить в один скрипт или управлять третьим скриптом, чтобы в командную строку нужно было вводить только одну команду? Я учусь и должен делать вещи, противоречащие передовой практике и правилам здесь!!!!! Большое спасибо, что уделили время и поделились своими знаниями на StackOverflow :-).

Другие вопросы по теме