нпм ERR! Отсутствует сценарий: встроить РЕАКЦИЮ, ОТКЛЮЧЕННУЮ В HEROKU - PullRequest
0 голосов
/ 04 сентября 2018

Я пытаюсь развернуть проект в Heroku с create-react-app, используя Node в качестве моего сервера и MongoDB для моей базы данных, но получаю ошибку. это мой первый проект с React. У меня 2 package.json файла. Один для create-react-app, другой для моего сервера узлов.

То, что я сделал, было:

  1. запустить сборку в React,
  2. коммит,
  3. создать приложение Heroku, используя heroku create -b https://github.com/mars/create-react-app-buildpack.git
  4. Я протолкнул его мастеру Героку.

Вот журналы.

Counting objects: 203, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (187/187), done.
Writing objects: 100% (203/203), 191.40 KiB | 5.80 MiB/s, done.
Total 203 (delta 91), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote: 
remote: -----> React.js (create-react-app) multi app detected
remote: -----> Configure create-react-app build environment
remote:        Using `NODE_ENV=development`
remote: =====> Downloading Buildpack: https://github.com/heroku/heroku-buildpack-multi.git
remote: =====> Detected Framework: Multipack
remote: =====> Downloading Buildpack: https://github.com/heroku/heroku-buildpack-nodejs.git
remote: =====> Detected Framework: Node.js
remote: 
remote: -----> Creating runtime environment
remote:        
remote:        NPM_CONFIG_LOGLEVEL=error
remote:        NPM_CONFIG_PRODUCTION=false
remote:        NODE_VERBOSE=false
remote:        NODE_ENV=development
remote:        NODE_MODULES_CACHE=true
remote: 
remote: -----> Installing binaries
remote:        engines.node (package.json):  unspecified
remote:        engines.npm (package.json):   unspecified (use default)
remote:        
remote:        Resolving node version 8.x...
remote:        Downloading and installing node 8.11.4...
remote:        Using default npm version: 5.6.0
remote: 
remote: -----> Restoring cache
remote:        Skipping cache restore (not-found)
remote: 
remote: -----> Building dependencies
remote:        Installing node modules (package.json + package-lock)
remote:        added 85 packages in 3.391s
remote: 
remote: -----> Caching build
remote:        Clearing previous node cache
remote:        Saving 2 cacheDirectories (default):
remote:        - node_modules
remote:        - bower_components (nothing to cache)
remote: 
remote: -----> Pruning devDependencies
remote:        Skipping because NODE_ENV is not 'production'
remote: 
remote: -----> Build succeeded!
remote: =====> Downloading Buildpack: https://github.com/mars/create-react-app-inner-buildpack.git
remote: =====> Detected Framework: React.js (create-react-app)
remote:        Writing `static.json` to support create-react-app
remote:        Enabling runtime environment variables
remote: npm ERR! missing script: build
remote: 
remote: npm ERR! A complete log of this run can be found in:
remote: npm ERR!     /app/.npm/_logs/2018-09-04T05_56_24_845Z-debug.log
remote:  !     Push rejected, failed to compile React.js (create-react-app) multi app.
remote: 
remote:  !     Push failed
remote: Verifying deploy...
remote: 
remote: !   Push rejected to klikie.
remote: 
To https://git.heroku.com/klikie.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/klikie.git

это мой package.json в приложении create-реакции-приложение

{
  "name": "klikme",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:8000/",
  "dependencies": {
    "react": "^16.4.2",
    "react-dom": "^16.4.2",
    "react-router-dom": "^4.3.1",
    "react-scripts": "1.1.5",
    "styled-components": "^3.4.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

это для моего сервера dep:

{
  "name": "klikme",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.3",
    "mongoose": "^5.2.12",
    "morgan": "^1.9.0"
  }
}

Я тоже добавил это на свой сервер, так как в документации:

app.use(express.static(path.join(__dirname, 'client/build')));
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});

1 Ответ

0 голосов
/ 04 сентября 2018

Итак, пару вещей, которые я заметил, основаны на том, что вы поделились здесь. Вы не используете раздел engines вашего package.json файла, чтобы указать версию Node.js для использования в Heroku. Это будет выглядеть примерно так:

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "engines": {
    "node": "9.3.0",
    "npm": "5.6.0"
  },

Вы также увидите выделенную выше версию npm, Node.js поставляется в комплекте с npm, поэтому в большинстве случаев вам не нужно указывать отдельную версию npm. Однако, если вы намеренно используете другую версию npm локально, вы можете указать ту же версию npm в Heroku.

Наконец, есть шаги сборки Heroku, и я не вижу этого в вашем основном файле package.json. Имейте в виду, что то, что я написал здесь, не относится к вашему файлу create-react-app package.json, потому что оно будет удалено при развертывании в Heroku. create-react-app перестанет существовать в Heroku.

Так что для конкретных действий Heroku вы захотите добавить что-то вроде этого в ваш основной package.json файл:

"heroku-postbuild":
      "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"

Что касается того, что вы добавили на свой сервер, попробуйте написать это так:

if (process.env.NODE_ENV === 'production') {
  // Express will serve up production assets
  // like main.js or main.css
  app.use(express.static('client/build'));

  // Express will serve up the index.html file if
  // it doesnt recognize the route
  const path = require('path');
  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
  });
}

Кроме того, я предполагаю, что это в вашем основном файле index.js, и вы также должны иметь эти две строки кода в нижней части файла:

const PORT = process.env.PORT || 5000;
app.listen(PORT);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...