Code Monkey home page Code Monkey logo

play-scala-react-seed's Introduction

MIT License

Scala Play React Seed

Use play framework to develop the web application backend/services and frontend using React Create App, all in a totally integrated workflow and single unified console. This approach will deliver perfect development experience without CORS hassle.

Read more @ http://bit.ly/2A1AzEq

Scala Play React Seed

Version Summary

How to use it?

Prerequisites

Let's get started,

  • Fork or clone this repository.

  • Used any of the following SBT commands which will intern trigger frontend associated npm scripts.

    sbt clean           # Clean existing build artifacts

    sbt stage           # Build your application from your project’s source directory

    sbt run             # Run both backend and frontend builds in watch mode

    sbt dist            # Build both backend and frontend sources into a single distribution artifact

    sbt test            # Run both backend and frontend unit tests
  • This seed is not using scala play views. All the views and frontend associated routes are served via React code base under ui directory.

Complete Directory Layout

├── /app/                                 # The backend (scala play) sources (controllers, models, services)
│     └── /controllers/                   # Backend controllers
│           └── FrontendController.scala  # Asset controller wrapper serving frontend assets and artifacts
├── /conf/                                # Configurations files and other non-compiled resources (on classpath)
│     ├── application.conf                # Play application configuratiion file.
│     ├── logback.xml                     # Logging configuration
│     └── routes                          # Routes definition file
├── /logs/                                # Log directory
│     └── application.log                 # Application log file
├── /project/                             # Contains project build configuration and plugins
│     ├── FrontendCommands.scala          # Frontend build command mapping configuration
│     ├── FrontendRunHook.scala           # Forntend build PlayRunHook (trigger frontend serve on sbt run)
│     ├── build.properties                # Marker for sbt project
│     └── plugins.sbt                     # SBT plugins declaration
├── /public/                              # Frontend build artifacts will be copied to this directory
├── /target/                              # Play project build artifact directory
│     ├── /universal/                     # Application packaging
│     └── /web/                           # Compiled web assets
├── /test/                                # Contains unit tests of backend sources
├── /ui/                                  # React frontend source (based on Create React App)
│     ├── /public/                        # Contains the index.html file
│     ├── /node_modules/                  # 3rd-party frontend libraries and utilities
│     ├── /src/                           # The frontend source codebase of the application
│     ├── .editorconfig                   # Define and maintain consistent coding styles between different editors and IDEs
│     ├── .gitignore                      # Contains ui files to be ignored when pushing to git
│     ├── package.json                    # NPM configuration of frontend source
│     ├── README.md                       # Contains all user guide details for the ui
│     └── yarn.lock                       # Yarn lock file
├── .gitignore                            # Contains files to be ignored when pushing to git
├── build.sbt                             # Play application SBT configuration
├── LICENSE                               # License Agreement file
├── README.md                             # Application user guide
└── ui-build.sbt                          # SBT command hooks associated with frontend npm scripts 

What is new in here?

FrontendCommands.scala

  • Frontend build command mapping configuration.
    ├── /project/
    │     ├── FrontendCommands.scala

FrontendRunHook.scala

  • PlayRunHook implementation to trigger npm run start on sbt run.
    ├── /project/
    │     ├── FrontendRunHook.scala

FrontendController.scala

  • Asset controller wrapper serving frontend assets and artifacts.
    ├── /app/                                 
    │     └── /controllers/                   
    │           └── FrontendController.scala

ui-build.sbt

  • This file contains the build task hooks to trigger frontend npm scripts on sbt command execution.

npm run commands

├── /ui/                       
│     ├── package.json          

Routes

├── /conf/      
│     ├── routes
  • The following route configuration map index.html to entry route (root). This should be placed as the initial route.
GET        /             controllers.FrontendController.index()
  • All API routes should be prefixed with API prefix defined under application.conf (Default prefix apiPrefix = "api")

Example API route:

GET        /api/summary  controllers.HomeController.appSummary
  • The following route is being used to serve frontend associated build artifacts (css, js) and static assets (images, etc.). This should be placed as the final route.
GET        /*file        controllers.FrontendController.assetOrDefault(file)

Note: On production build all the front end React build artifacts will be copied to the public folder.

Can be used to implement any front end/ui build!

  • Simply replace the ui directory with the build of your choice
  • Make output directory ROOT/public/
  • Implement a proxy to localhost:9000

Looking for some other frontend framework or language choice

License

This software is licensed under the MIT license

play-scala-react-seed's People

Contributors

aravindakr95 avatar arty26 avatar billyautrey avatar dependabot[bot] avatar deprosun avatar duncannevin avatar ganeshchand avatar gavinbaumanis avatar lahiruz avatar mkurz avatar ptrdom avatar scala-steward avatar sunpj avatar theilig avatar yohangz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

play-scala-react-seed's Issues

How to handle fork with TypeScript

I've created a fork of this repo using TypeScript instead of vanilla JS and changing some things to make them more modern, like using hooks, async/await instead of callbacks, etc.

https://github.com/toddobryan/scala-play-react-typescript-seed

I'm happy to share this back, but I don't know if that's the right thing to do or how to do it. Some people might not want TypeScript, so I don't know if you want to create different branches on this repo or if I should just keep my fork separate and maybe you could include a link for people who are interested in TypeScript.

Just let me know the easiest way to deal with this, and I'm happy to oblige.

Upgrade to sbt 1.1.1?

#The arrow keys don't work in the sbt console for sbt 1.0.3. This has been fixed for sbt 1.1.1:

sbt/sbt#3788

Here are the changes that are necessary to upgrade this project to use sbt 1.1.1:

  1. in project/build.properties
    sbt.version=1.1.1

  2. in ui-build.sbt
    change TaskKey to taskKey

Thanks!

sbt run causing an error related to BABEL. It can't find `./src/data`

[info] Loading settings for project scala-play-react-seed-build from plugins.sbt ...
[info] Loading project definition from /Users/fahad/Projects/scala-play-react-seed/project
[info] Loading settings for project root from ui-build.sbt,build.sbt ...
[info] Set current project to scala-play-react-seed (in build file:/Users/fahad/Projects/scala-play-react-seed/)
[info] Updating ...
[info] Done updating.
[warn] There may be incompatibilities among your library dependencies; run 'evicted' to see detailed eviction warnings.

--- (Running the application, auto-reloading is enabled) ---

[info] p.c.s.AkkaHttpServer - Listening for HTTP on /0:0:0:0:0:0:0:0:9000

(Server started, use Enter to stop and go back to the console...)


> [email protected] start /Users/fahad/Projects/scala-play-react-seed/ui
> react-scripts start

Starting the development server...

Failed to compile.

./node_modules/react-dev-utils/webpackHotDevClient.js
Error: [BABEL] /Users/fahad/Projects/scala-play-react-seed/ui/node_modules/react-dev-utils/webpackHotDevClient.js: Cannot find module './src/data' (While processing: "/Users/fahad/Projects/scala-play-react-seed/ui/node_modules/babel-preset-react-app/dependencies.js$0$9")

NPM 6.9.0
Node.js v10.16.3

Action Not Found For request 'GET /'

Hello, I'm trying to run scala-play-react-seed and get the following errors:

  1. Before updating packages in package.json loading localhost:9000 in browser gave me the following output:
    TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined

  2. After updating packages in package.json I've got:

    Action Not Found
    For request 'GET /'
    These routes have been tried, in this order:
    1 GET / controllers.FrontendController.index()
    2 GET / api/summary controllers.HomeController.appSummary
    3 GET / $file<.+> controllers.FrontendController.assetOrDefault(file:String)

Deployment to Heroku requires package.json under root directory

Hi,
I'm trying to deployment the app to Heroku.
I already added buildpack "https://github.com/mars/create-react-app-buildpack" to the application
But it doesn't work since the package.json is placed under ui/ instead of the root directory.

So the build system complains that " App not compatible with buildpack: https://github.com/mars/create-react-app-buildpack.git"
Is there any solution other than duplicating the file or create a symbol link?

Thanks

react-scripts: not found

I use SBT run returns

sh: 1: react-scripts: not found
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! [email protected] start: react-scripts start
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

`npm run build` is not hooked

First and foremost, this project is a great seed!

  1. Given: '/' is project root
    I might be getting the context wrong here but it seems that I can't have my /public updated upon file changes in /ui/src/*. Could be probably be related to build.sbt on line ..watchSources ++= (baseDirectory.value / "public/ui" ** "*").get? I don't see the relevancy of /public/ui here

  2. Might be a good idea on generating the public assets onBefore cycle (localhost:9000/ won't work when there is no index.html)
    FrontendRunHook.scala:

      override def beforeStarted(): Unit = {
        if (!(base / "ui" / "node_modules").exists()) Process(yarnInstall, base / "ui").!
        if (!(base / "public").exists()) Process(npmBuild, base / "ui").!
      }

Please clarify things for me, I can help with pull requests!

"sbt test" hangs when "npm run test" is waiting for user input

When running sbt test, npm run test is first executed in watch mode, but it cannot receive user input so it hangs.

The workaround I found is to disable watch mode by enabling CI, with CI=true. That is in package.json change the line test like so:

  "scripts": {
    "start": ...,
    "build": ...,
    "test": "CI=true react-scripts test --env=jsdom",
    ...
   }

I haven't figured out how to let Process() receive input from standard input.

How do you get the Play server to stop? Ctrl-C only stops React, it seems...

When I sbt run in the terminal and then Ctrl-C to quit, I get

[warn] Canceling execution...

but it never finishes and the Play server keeps running. I can't re-run things because I get a BindException since port 9000 is still being used.

I'm doing this in the IntelliJ sbt shell, and quitting the shell doesn't work. I have to completely quit IntelliJ to get the process to release the port.

Running in a separate terminal, the same thing happens. Supposedly, you can exit out of the Play server by pressing enter, but that doesn't seem to work at all. At least with the terminal, if I exit out of the terminal then the Play server releases the port so I can sbt run again.

Anyone else having this problem or am I just doing something silly?

controllers.Assets.at returns 404 when looking for a React route

Your solution is very clever and I managed to merge a non trivial React application into a Play application.

There was one problem, though. React routes (that are not resources) are obviously not found by controllers.Assets.at() which returns 404. It should return the main page index.html that processes the routes correctly.

This problem is explained in issue #7634 of Playframework.

A solution I found is to implement a controller like so:

@Singleton
class SpaController @Inject()(assets: Assets,
                              cc: ControllerComponents)
                             (implicit ec: ExecutionContext)
  extends AbstractController(cc) {

  def index = assets.at("index.html")

  def assetOrDefault(resource: String) = if (resource.contains(".")) assets.at(resource) else index
}

and add these routes to the routes file:

# first route
GET        /             controllers.SpaController.index()

# last route
GET        /*file        controllers.SpaController.assetOrDefault(file)

Is this repository dead?

I wanted to add some improvements to the setup, but the last commit to master was a while ago, and there already are beneficial PRs that seem to be stale, so I wonder if I should just fork it instead of producing a PR here and continue the work on this template in a new repository.

Thoughts?

sbt stage and sbt dist fail

The error

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `rimraf ../public && react-scripts build && ncp build ../public && rimraf build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] 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!     /Users/avremel/.npm/_logs/2018-12-17T16_29_02_578Z-debug.log
[error] java.lang.Exception: Oops! UI Build crashed.
[error] 	at $5340de8abc0aeaad481e$.$anonfun$$sbtdef$1(/Users/avremel/Desktop/scala_react/ui-build.sbt:56)
[error] 	at $5340de8abc0aeaad481e$.$anonfun$$sbtdef$1$adapted(/Users/avremel/Desktop/scala_react/ui-build.sbt:54)
[error] 	at scala.Function1.$anonfun$compose$1(Function1.scala:44)
[error] 	at sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:39)
[error] 	at sbt.std.Transform$$anon$4.work(System.scala:66)
[error] 	at sbt.Execute.$anonfun$submit$2(Execute.scala:262)
[error] 	at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)
[error] 	at sbt.Execute.work(Execute.scala:271)
[error] 	at sbt.Execute.$anonfun$submit$1(Execute.scala:262)
[error] 	at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:174)
[error] 	at sbt.CompletionService$$anon$2.call(CompletionService.scala:36)
[error] 	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error] 	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
[error] 	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error] 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
[error] 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
[error] 	at java.lang.Thread.run(Thread.java:748)
[error] (uiProdBuild) java.lang.Exception: Oops! UI Build crashed.

This is the verbose log:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/Cellar/node/11.4.0/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'run',
1 verbose cli   'build' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle [email protected]~prebuild: [email protected]
6 info lifecycle [email protected]~build: [email protected]
7 verbose lifecycle [email protected]~build: unsafe-perm in lifecycle true
8 verbose lifecycle [email protected]~build: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/avremel/Desktop/scala_react/ui/node_modules/.bin:/usr/local/opt/[email protected]/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
9 verbose lifecycle [email protected]~build: CWD: /Users/avremel/Desktop/scala_react/ui
10 silly lifecycle [email protected]~build: Args: [ '-c',
10 silly lifecycle   'rimraf ../public && react-scripts build && ncp build ../public && rimraf build' ]
11 silly lifecycle [email protected]~build: Returned: code: 1  signal: null
12 info lifecycle [email protected]~build: Failed to exec build script
13 verbose stack Error: [email protected] build: `rimraf ../public && react-scripts build && ncp build ../public && rimraf build`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:189:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:189:13)
13 verbose stack     at maybeClose (internal/child_process.js:978:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:265:5)
14 verbose pkgid [email protected]
15 verbose cwd /Users/avremel/Desktop/scala_react/ui
16 verbose Darwin 17.7.0
17 verbose argv "/usr/local/Cellar/node/11.4.0/bin/node" "/usr/local/bin/npm" "run" "build"
18 verbose node v11.4.0
19 verbose npm  v6.4.1
20 error code ELIFECYCLE
21 error errno 1
22 error [email protected] build: `rimraf ../public && react-scripts build && ncp build ../public && rimraf build`
22 error Exit status 1
23 error Failed at the [email protected] build script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

Passing environment variable to React app

Hi There,

Is there way to pass environment variables to React app? In our application we need to pass an environment variable to React app. Usually in React app the environment variable must prefix REACT_APP_, but passing variable at run time doesn't work.
There is option to have environment specific files but then you need different Docker image for each application.

Any solution to this your mind?

Regards,

Syed

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

It should be possible to start the front end and back end with a single command

This is a description of how the project works for me under Mac OS X Catalina, along with a suggestion of how I think it should work.

  • From the root directory, I start the back end with the command sbt run

  • After everything is built and the server has started, the following output appears in the console:

> [email protected] start /Users/peter/CodeRoot/other/scala-play-react-seed/ui
> react-scripts start

ℹ 「wds」: Project is running at http://10.0.0.69/
ℹ 「wds」: webpack output is served from 
ℹ 「wds」: Content not from webpack is served from /Users/peter/CodeRoot/other/scala-play-react-seed/ui/public
ℹ 「wds」: 404s will fallback to /
Starting the development server...
  • The browser now opens at the url http://localhost:3000/. This page is blank, and the error message in Chrome is as follows:
This site can’t be reached
localhost refused to connect.
  • I open a new console and execute the following:
cd ui
npm start

The output in the new console is as follows:

Compiled successfully!

You can now view hivetest in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://10.0.0.69:3000

Note that the development build is not optimized.
To create a production build, use yarn build.
  • The browser automatically reloads http://localhost:3000/ and displays the React application as expected.

I would have expected the last stage to happen automatically, making the manual step unnecessary.

Question: about watchSources

Hi in your build.sbt there is this line

  watchSources ++= (baseDirectory.value / "public/ui" ** "*").get

May I know what does it do ?? There isn't a folder at public/ui

Best,

Allow for backend and integration tests

Currently sbt test runs both frontend and backend tests, there should be a way to run the tests in more granular fashion - separate tasks for frontend, backend and integration tests. Integration tests should allow for full application tests, one way to achieve that would be to run them on a production build, which would bundle frontend within the backend.

Failure on running 'stage' or 'dist' because of 'env CI=true' !!!

npm ERR! [email protected] build: `rimraf ../public && react-scripts build && ncp build ../public && rimraf build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script 'rimraf ../public && react-scripts build && ncp build ../public && rimraf build'.

I faced this error while I was trying to make a package; I tried to run rimraf ../public && react-scripts build && ncp build ../public && rimraf build manually in terminal and I got that non of rimraf, react-scripts, and ncp was not installed (at least they wan't in my PATH)! I installed those with -g flag and tried it again in CLI and everything worked! then I got back to sbt and tried to run stage and I get the error again.
Finally when I remove the string concatenation of env CI=true in runOnCommandline the sbt did the job:

// Execute on commandline, depending on the operating system. Used to execute npm commands.
def runOnCommandline(script: String)(implicit dir: File): Int = {
  if(isWindows){ Process("cmd /c set CI=true&&" + script, dir) } else { Process(/*"env CI=true " +*/ script, dir) } }!

It's weird! As I understand it should not be needed to install rimraf, react-scripts, and ncpmanually (and with -g tag!!!) and I didn't need to remove the CI=true environment variable to run it properly!

Is something wrong with my installation? Or should I provide more information?

[email protected]
node version: v8.10.0
npm version: 3.5.2

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.