Create-React-App v2 с модулями Node-SASS и CSS работает локально, но вылетает в Heroku

#css #reactjs #sass #create-react-app #react-css-modules

#css #reactjs #sass #create-react-app #react-css-modules

Вопрос:

Я использую Create-React-App v2 и установил node-sass . Я также хочу использовать модули CSS, поэтому я изменил расширения и импорт на .module.scss .

Примечание: Я импортировал переменные (_color.scss, _type.scss) в таблицы стилей каждого компонента, но это не работает, поэтому я вручную импортировал каждую необходимую переменную в таблицу стилей каждого компонента на данный момент.

Итак, теперь приложение работает локально, но вылетает в Heroku. Heroku logs состояния build failed и предоставляет 3 ссылки на выходные данные сборки для устранения неполадок. Вот следующие результаты сборки.

ВЫВОД 1-Й СБОРКИ

 -----> Node.js app detected

-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       NODE_ENV=production
       NODE_MODULES_CACHE=true
       NODE_VERBOSE=false

-----> Installing binaries
       engines.node (package.json):  unspecified
       engines.npm (package.json):   unspecified (use default)

       Resolving node version 10.x...
       Downloading and installing node 10.15.3...
       Using default npm version: 6.4.1

-----> Restoring cache
       - node_modules

-----> Installing dependencies
       Installing node modules (package.json   package-lock)
       audited 36784 packages in 17.665s
       found 63 low severity vulnerabilities
         run `npm audit fix` to fix them, or `npm audit` for details

-----> Build
       Running build

       > webportfolio@0.1.0 build /tmp/build_946ff21a3c8a665eda74215ba467f646
       > react-scripts build

       Creating an optimized production build...
       Failed to compile.

       ./src/App.js
       Cannot find file './Components/Portfolio/Portfolio' in './src'.


npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! webportfolio@0.1.0 build: `react-scripts build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the webportfolio@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /tmp/npmcache.EQOTa/_logs/2019-03-11T23_54_27_075Z-debug.log
-----> Change to Node.js build process 
       Heroku has begun executing the "build" script defined in package.json
       during Node.js builds.
       Read more: https://devcenter.heroku.com/changelog-items/1573
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       Some possible problems:

       - Node version not specified in package.json
         https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version

       Love,
       Heroku

 !     Push rejected, failed to compile Node.js app.
 !     Push failed
  

ВЫВОД 2-Й СБОРКИ

 -----> Node.js app detected

-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       NODE_ENV=production
       NODE_MODULES_CACHE=true
       NODE_VERBOSE=false

-----> Installing binaries
       engines.node (package.json):  unspecified
       engines.npm (package.json):   unspecified (use default)

       Resolving node version 10.x...
       Downloading and installing node 10.15.3...
       Using default npm version: 6.4.1

-----> Restoring cache
       - node_modules

-----> Installing dependencies
       Installing node modules (package.json   package-lock)
       audited 36784 packages in 17.814s
       found 63 low severity vulnerabilities
         run `npm audit fix` to fix them, or `npm audit` for details

-----> Build
       Running build

       > webportfolio@0.1.0 build /tmp/build_85b1987ab543478c5aee6f4728e8b330
       > react-scripts build

       Creating an optimized production build...
       Failed to compile.

       ./src/App.js
       Cannot find file './Components/Portfolio/Portfolio' in './src'.


npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! webportfolio@0.1.0 build: `react-scripts build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the webportfolio@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /tmp/npmcache.htJgH/_logs/2019-03-12T00_00_58_185Z-debug.log
-----> Change to Node.js build process 
       Heroku has begun executing the "build" script defined in package.json
       during Node.js builds.
       Read more: https://devcenter.heroku.com/changelog-items/1573
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       Some possible problems:

       - Node version not specified in package.json
         https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version

       Love,
       Heroku

 !     Push rejected, failed to compile Node.js app.
 !     Push failed
  

ВЫВОД ТРЕТЬЕЙ СБОРКИ

 -----> Node.js app detected

-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       NODE_ENV=production
       NODE_MODULES_CACHE=true
       NODE_VERBOSE=false

-----> Installing binaries
       engines.node (package.json):  10.5.0
       engines.npm (package.json):   unspecified (use default)

       Resolving node version 10.5.0...
       Downloading and installing node 10.5.0...
       Using default npm version: 6.1.0

-----> Restoring cache
       Cached directories were not restored due to a change in version of node, npm, yarn or stack
       Module installation may take longer for this build

-----> Installing dependencies
       Installing node modules (package.json   package-lock)

       > node-sass@4.11.0 install /tmp/build_17cf925c197f17907d43d6369284d804/node_modules/node-sass
       > node scripts/install.js

       Downloading binary from https://github.com/sass/node-sass/releases/download/v4.11.0/linux-x64-64_binding.node
       Download complete
       Binary saved to /tmp/build_17cf925c197f17907d43d6369284d804/node_modules/node-sass/vendor/linux-x64-64/binding.node
       Caching binary to /tmp/npmcache.Dfkzs/node-sass/4.11.0/linux-x64-64_binding.node

       > node-sass@4.11.0 postinstall /tmp/build_17cf925c197f17907d43d6369284d804/node_modules/node-sass
       > node scripts/build.js

       Binary found at /tmp/build_17cf925c197f17907d43d6369284d804/node_modules/node-sass/vendor/linux-x64-64/binding.node
       Testing binary
       Binary is fine
       added 1883 packages from 750 contributors and audited 36784 packages in 39.346s
       found 63 low severity vulnerabilities
         run `npm audit fix` to fix them, or `npm audit` for details

-----> Build
       Running build

       > webportfolio@0.1.0 build /tmp/build_17cf925c197f17907d43d6369284d804
       > react-scripts build

       Creating an optimized production build...
       Failed to compile.

       ./src/App.js
       Cannot find file './Components/Portfolio/Portfolio' in './src'.


npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! webportfolio@0.1.0 build: `react-scripts build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the webportfolio@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /tmp/npmcache.Dfkzs/_logs/2019-03-12T01_08_21_381Z-debug.log
-----> Change to Node.js build process 
       Heroku has begun executing the "build" script defined in package.json
       during Node.js builds.
       Read more: https://devcenter.heroku.com/changelog-items/1573
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       If you're stuck, please submit a ticket so we can help:
       https://help.heroku.com/

       Love,
       Heroku

 !     Push rejected, failed to compile Node.js app.
 !     Push failed
  

Решения, которые я пытался:

Я застрял на некоторое время и был бы очень признателен за любую помощь. Заранее спасибо!

Пакет установлен

Node.js v10.15.3 to /usr/local/bin/node
• npm v6.4.1 to /usr/local/bin/npm
  

Комментарии:

1. Вот ваша проблема: Cannot find file './Components/Portfolio/Portfolio' in './src'. измените эту строку: github.com/KenAustria/WebPortfolio/blob/master/src/App.js#L2 на import Portfolio from './components/Portfolio/Portfolio'; .

2. @MattCarlotta Прошу прощения, в нижнем регистре ‘c’ в компонентах произойдет сбой, поскольку папка называется ‘Components’? Я попробовал, и ему не удалось скомпилировать, как ожидалось.

3. Что было сообщением об ошибке? Согласно вашему репозиторию github, это components , не Components . Смотрите: github.com/KenAustria/WebPortfolio/tree/master/src/components

4. @MattCarlotta Да, прошу прощения, вы правы. В моем редакторе это с C и не c . Когда я меняю его на c , это выдает мне эту ошибку. Failed to compile: Cannot find file: 'Portfolio.js' does not match the corresponding name on disk: './src/components/Portfolio/Components'.

5. У вас довольно много ошибок, которые необходимо устранить. Разветвленный репозиторий, скоро должна появиться исправленная версия.

Ответ №1:

Хорошо … этому проекту требуется большая переработка таблицы стилей.

Все ваши файлы на уровне компонентов .scss должны находиться в той же папке, что и component , для которой это требуется. Любые частичные файлы должны быть импортированы в scss уровня компонента, которому они нужны. Некоторые из ваших таблиц стилей делают это, но некоторые нет. Кроме того, по какой-либо причине вы импортируете части в css таблицу стилей и импортируете части в scss таблицы стилей. Просто придерживайтесь scss таблиц стилей!

Подводя итог:

  • Любая таблица стилей, которая должна использоваться component , должна находиться в той же папке, что и component .
  • Любая таблица стилей, которая должна использоваться многими компонентами, должна быть частичным файлом, импортируемым в таблицу стилей на уровне компонента.

Прямо сейчас у вас есть частичные элементы, такие как _app_portfolio.scss файлы на Sass уровне Portfolio.module.scss и таблицы стилей на уровне компонентов, для Portfolio.js которых требуются отдельно. Это антипаттерн. Фрагменты должны представлять собой таблицы стилей повторного использования, которые будут импортированы в таблицы стилей на уровне нескольких компонентов для повторного использования.

Например, вы должны структурировать свое приложение следующим образом: (для простоты ваши папки основного каталога должны быть в нижнем регистре):

 ├── src
|   ├── components
|   |   └── Portfolio
|   |       ├── Portfolio.js
|   |       └── Portfolio.scss  (non-partial file, this component-level stylesheet contains all of styles required for Portfolio.js)
|   |   
|   ├── images
|   ├── styles
|   |   ├── base
|   |   |   └── _base.scss (partial file, include any DOM-level styles like "a" or "p", or "div", "body", "html" ... etc.)
|   |   |
|   |   ├── exts
|   |   |   └── _extensions.scss (partial file, include any extended styles like ".clear fix", which is a classname that'll contain repetitive style patterns)
|   |   |
|   |   ├── globals
|   |   |   └── globals.scss (non-partial file, include any GLOBAL stylesheets, like "normalize.css", this stylesheet will be directly imported into ./src/index.js like so: import "./styles/globals/globals.scss";)
|   |   |
|   |   ├── mixins
|   |   |   └── _mixins.scss (partial file, define your mixins that'll be shared with component-level scss)
|   |   |
|   |   ├── vars
|   |   |   └── _vars.scss (partial file, define your variables that'll be shared with component-level scss)
|   |   |
|   |   └── index.scss (OPTIONAL non-partial file that imports all of the partial files above, then this file can be imported into a component-level stylesheet. Instead of writing 4 imports for base, exts, mixins and vars, you'll just do: @import '../path/to/styles/index.scss'; now you have included all 4 partials within 1 import)
|   |
|   └── index.js
  

Как реализовать вышеуказанное…

components/Portfolio/Portfolio.js

 import React from "react";
import Profile from "../Profile/Profile";
import { portfolioContainer } from "./Portfolio.scss"; // import the className, if there are many classes, then just import them as "styles" from './stylesheet.scss'; then use: "styles.portfolioContainer", "styles.example", "styles.example2" ...etc

const Portfolio = () => {
  return (
    <div className={portfolioContainer}>
      <Profile />
    </div>
  );
};

export default Portfolio;
  

компоненты / Портфолио/Portfolio.scss

 @import '../../styles/vars/vars.scss'; // partial file import, now we can use $variables
@import '../../styles/mixins/mixins.scss'; // partial file import, now we can use @include mixinname();
@import '../../styles/exts/extensions.scss'; // partial file import, now we can use @extend .classname;

.portfolioContainer {
  @include grid-template-columns(1);
  color: $brightgreen;
  background: url('../../images/example.png'); // include your image imports within the component-level stylesheet -- if you import it in a partial file, then import that partial within a stylesheet, then you'll run into some pathing issues. The path defined will be relative to the partial and won't be an absolute path to the image when imported within the component-level stylesheet.
  display: flex;
  flex-flow: column wrap;
  height: 100vh;

  amp;::after {
    @extend .clear-fix;
  }
}
  

Взгляните на это руководство по основам Sass.

Если вам трудно разобраться, пожалуйста, ознакомьтесь с моим react-starter-kit, который включает заметки в styles / index.scss и styles / globals / globals.scss и как использовать частичные элементы в components / Home / Home.scss и импортировать в components/Home/Home.js и как использовать глобальные переменные в src/index.js .

Поскольку вы используете create-react-app , вам может понадобиться sass-компилятор для компиляции .scss файлов в один или несколько .css файлов. К сожалению, я не использую CRA, поэтому вам придется погрузиться в документы, чтобы узнать, как.

Комментарии:

1. Я не могу оценить вас достаточно! Я собираюсь реализовать то, что вы посоветовали, и вернусь с результатами.

2. Нет проблем! Если вы застряли, не стесняйтесь спрашивать.

3. Это работает! Я благодарен за усилия, которые вы предприняли, чтобы помочь мне понять мои ошибки. Я бы хотел угостить вас кофе (электронное пожертвование). Пожалуйста, дайте мне знать, как это сделать. Еще раз спасибо!

4. Рад, что вы во всем разобрались! Поздравляю! Если вы хотите угостить меня кофе, вы можете найти ссылку в описании моего профиля. Удачного кодирования.