Symfony 4, include assets from vendor directory - php

I would like to load vendor assets, downloaded with composer inside vendor directory, from my twig template.
Using a relative path is one solution (in this example I'm going to include bootstrap css, but the same problem is for any other libs required from composer, as jQuery, jQueryUI etc. )
<link rel="stylesheet" href="{{ asset('../vendor/twbs/bootstrap/dist/css/bootstrap.min.css') }}" >
Symfony docs suggest to use asset:install in order to generate a symlink from vendor directory to public, but I was unable to understand how it works.
assets:install -h wasn't so clear to let me understand how to link a specific vendor path to the public directory.
Creating a simlink with
ln -s /path/of/vendor/lib /path/public/dir
works fine but, symlinks created will be deleted every time I look for an update with composer.
Any idea about "a best practice" to include assets from vendor directory?
Thank you

In terms of 'Best Practice', I generally use npm with gulp or something to that effect, which generates distribution css and js files that are output to a designated file in public/.
Here's an example from a recent project package.json file
{
"devDependencies": {
"bootstrap": "^4.1.3",
"gulp": "^4.0.0",
"gulp-concat": "^2.6.1",
"gulp-sass": "^3.1.0"
},
"scripts": {
"compile:styles": "gulp styles"
}
}
Rather run npm install --save-dev bootstrap gulp gulp-concat gulp-sass to get the latest versions etc.
And you'll need this gulpfile.js too
var gulp = require('gulp');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
gulp.task('styles', function(){
return gulp
.src([
'app/Resources/sass/main.scss',
])
.pipe(sass({outputStyle:'compressed', includePaths: ['node_modules']}).on('error', sass.logError))
.pipe(concat('styles.min.css'))
.pipe(gulp.dest('public/css'));
});
Once setup, you can run npm run compile:styles from the console and the app/Resources/sass/main.scss SASS file will be pre-processed, minified and output to public/css/styles.min.css.
Note that the gulp file includes the node_modules folder so you can import bootstrap inside the main.scss file, e.g.
$primary: #55a367;
#import 'bootstrap/scss/bootstrap';
From a twig template:
<link rel="stylesheet" type="text/css" href="{{ asset('css/styles.min.css') }}">
I generally commit both the main.scss and styles.min.css

The reason why you can't tell the assets:install to link and arbitrary vendor directory is that the command is designed to loop through the list of installed bundles and link a well-known directory (Resources/public) directory if it exists. It relies on both the short bundle name and the directory existing, so it can only work with symfony bundles, there's no support for other libraries like bootstrap or jquery. (Link to current command source).
The recommended way to handle frontend libraries nowadays is encore.
In a situation where that's not possible, you could use composer scripts. I wouldn't call this "best practice", might end up being more trouble than it's worth but is an option you can consider.
You would create a shell, php script or console command where you basically replicate the functionality of assets:install to link your library assets. You will still need to manually update the script when you install a new library, but you can configure it to automatically run after installing or updating packages.
Copy this simple sample bash script into you project directory, name it install_vendors.sh:
#!/bin/bash
BASE_PATH=`pwd`
PUBLIC="public"
if [ "$1" != "" ]; then
PUBLIC=$1
fi;
PUBLIC=${BASE_PATH}/${PUBLIC}/vendor
VENDOR=${BASE_PATH}/vendor
rm $PUBLIC -rf
mkdir $PUBLIC
function link_asset
{
SOURCE_DIR=${VENDOR}/$1
TARGET_DIR=${PUBLIC}/$2
ln -s $SOURCE_DIR $TARGET_DIR
}
link_asset twbs/bootstrap/dist bootstrap
Add it to the scripts section of composer.json and the auto-scripts:
"scripts": {
"vendors:install": "bash install_vendors.sh",
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
"#vendors:install"
},
// ...
}
You can also execute it at any time with composer run vendors:install.
Then include them in your twig files: {{ asset('vendor/bootstrap/css/bootstrap.min.css') }}.

Related

How write a Symfony Flex recipe for a new bundle?

I tried to find any documentation about using Symfony Flex but so far no luck.
Almost all docs point to installing a bundle that uses symfony Flex, not how to create a bundle that is using it.
I even tried to reverse engineer some of the packages but again, no luck.
My goal is to generate a default configuration file for my bundle in config/packages/my_bundle.yaml.
What I need to know is where do I need to put it and what env variables (if any) will I have available?
What is a Flex Recipe?
Keep in mind that the flex recipe is a separate repository from your package repository, that needs to be hosted separately from the Bundle package.
In the most likely scenario that your is a public bundle/recipe, you'll have to submit your recipe to the "contrib" repository, get it approved and merged, so it's available as a community recipe.
Additionally, it's important to remember that most users will not have the contrib repository enabled by default. So if this is important for installing this bundle, you should tell your users how to do so before they install your recipe (e.g. in your bundle's readme file).
Private Recipes
The other option would be having a private Flex recipe, as described here. The easiest way to generate a private recipe is to follow the same steps that Symfony does. Check this question and its answers for more details: How to generate a private recipe JSON from the contents of a recipe directory?
With that out of the way: Basically, a Flex recipe is a repository with a manifest.json file with specific keys to enable certain "configurators".
The available manifest.json configurators are:
Bundles
Which bundles should be enabled on bundles.php. These are added when the recipe is installed, and removed when the recipe is uninstalled.
{
"bundles": {
"Symfony\\Bundle\\DebugBundle\\DebugBundle": ["dev", "test"],
"Symfony\\Bundle\\MonologBundle\\MonologBundle": ["all"]
}
}
Configuration
The "configuration" configurator deals with two keys: copy-from-recipe and copy-from-package. The first one can copy files from the recipe repository, the second one copies files from the package repository.
{
"copy-from-package": {
"bin/check.php": "%BIN_DIR%/check.php"
},
"copy-from-recipe": {
"config/": "%CONFIG_DIR%/",
"src/": "%SRC_DIR%/"
}
}
In this example, a file bin/check.php in the package will be copied to the projects %BIN_DIR%, and the contents of config and src on the recipe package will be copied the corresponding directory.
This is the typical use case to provide default configuration files, for example. From what you ask, this is your stated purpose for wanting to create a flex recipe.
Env Vars
This configurator simply adds the appropriate environment variable values to the project's .env and .env.dist. (Again, these would be removed if you uninstalled the recipe)
{
"env": {
"APP_ENV": "dev",
"APP_DEBUG": "1"
}
}
Composer Scripts
This configurator adds tasks to the scripts:auto-scripts array from the project's composer.json. The auto-scripts are tasks that are executed every time composer update or composer install are executed in the project.
{
"composer-scripts": {
"vendor/bin/security-checker security:check": "php-script",
"make cache-warmup": "script",
"assets:install --symlink --relative %PUBLIC_DIR%": "symfony-cmd"
}
}
The second part on each line specifies what kind of command it is: a regular PHP script (php-script), a shell script (script), or a Symfony command (symfony-cmd, executed via bin/console).
Gitignore
This will add entries to the project's .gitignore file.
{
"gitignore": [
"/phpunit.xml"
]
}
A complete example of a manifest.json (lifted from here, as most other examples on this post):
{
"bundles": {
"Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle": ["all"]
},
"copy-from-recipe": {
"config/": "%CONFIG_DIR%/",
"public/": "%PUBLIC_DIR%/",
"src/": "%SRC_DIR%/"
},
"composer-scripts": {
"make cache-warmup": "script",
"assets:install --symlink --relative %PUBLIC_DIR%": "symfony-cmd"
},
"env": {
"APP_ENV": "dev",
"APP_DEBUG": "1",
"APP_SECRET": "%generate(secret)%"
},
"gitignore": [
".env",
"/public/bundles/",
"/var/",
"/vendor/"
]
}
Additional configurators
There are two configurators which do not rely on the manifest.json file:
Post-install output.
If a file named post-install.txt exists in the recipe's package, its content is displayed when installation is complete. You can even use styles as defined here, for additional prettiness/obnoxiousness.
Example:
<bg=green;fg=white> </>
<bg=green;fg=white> Much success!! </>
<bg=green;fg=white> </>
* <fg=yellow>Next steps:</>
1. Foo
2. <comment>bar</>;
3. Baz <comment>https://example.com/</>.
This will be presented to the user after the installation is complete.
Makefile
If a file named Makefile exists in the recipe's repository, the tasks defined here would be added to the project's Makefile (creating the Makefile if it didn't exist).
cache-clear:
#test -f bin/console && bin/console cache:clear --no-warmup || rm -rf var/cache/*
.PHONY: cache-clear
Simple as that. I guess than most packages would not need a makefile command, so this would have much less use than other configurators.
You can read the full documentation here.

How to use rtlcss node package with twitter-bootstrap on Laravel?

It may sound stupid but I've recently started working with laravel mix for compiling scss and js files. But I can't understand something.
I want to use rtlcss npm to make the twitter-bootstrap rtl.
This is the default app.scss asset of Laravel
// Fonts
#import url("https://fonts.googleapis.com/css?family=Raleway:300,400,600");
// Variables
#import "variables";
// Bootstrap
#import "~bootstrap-sass/assets/stylesheets/bootstrap";
And this is the default app.js asset:
window._ = require('lodash');
try {
window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');
} catch (e) {}
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
I've installed the rtlCSS through node package, now I what I want to happen is when I run npm run dev or the watcher, it compiles the bootstrap scss file and make it RTL and put it in the public css directory like it does with the default LTR that is.
Your can easily generate RTL css with Laravel Mix:
First, to use Laravel mix you should install the necessary libraries from npm:
npm install
Then, install webpack-rtl-plugin: npm install webpack-rtl-plugin --save-dev
Then, in webpack.mix.js (located at the root of your laravel app) import the pulgin at the top:
let WebpackRTLPlugin = require('webpack-rtl-plugin');
Then, replace the:
mix.js('resources/assets/js/app.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css');
with the following:
mix.js('resources/assets/js/app.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css')
.webpackConfig({
plugins: [
new WebpackRTLPlugin()
]
});
Finally, run: npm run dev (for develpoment) or npm run prod (for production)
As a result, Larave Mix will generate:
public/css/app.css (the original css from sass)
public/css/app.rtl.css (the RTL css version)
and public/css/app.js
I tried multiple solutions with no luck after multiple tries the below code works fine and it covers all mix features like versioning, source-maps, etc.
Don't forget to install rtlcss package
mix.sass('resources/sass/app.scss', 'public/css');
mix.postCss('public/css/app.css', 'public/css/app.rtl.css', [
require('rtlcss'),
]);

The Mix manifest does not exist when it does exist

For my admin panel I extract all the assets including the manifest-json.js to mix.setPublicPath(path.normalize('public/backend/')).
All the files get correctly added to the backend folder, and the manifest-json.js file looks as follows:
{
// all correct here
"/js/vendor.js": "/js/vendor.js",
"/js/app.js": "/js/app.js",
"/css/app.css": "/css/app.css",
"/js/manifest.js": "/js/manifest.js"
}
the problem is that when using
{{ mix('backend/css/app.css') }}
in my blade-files, it looks in public/manifest-json.js instead of looking for it in backend/manifest-json.js.
How can I make sure the right manifest-json.js file is used?
I had same exception after deployment laravel project to server. It was working perfectly fine on localhost but after lot of research I found a solution. If you encounter this exception on server then you have to bind your public path to public_html
Just go to under the app/Providers, you will find your AppServiceProvider file and inside boot() method make the binding as below.
$this->app->bind('path.public', function() {
return base_path().'/../public_html';
});
i solved my problem running this command
npm install
and then
npm run production
Thank You.
The problem I faced was that the mix()-helper function by default looks for the manifest-json file in /public/manifest-json.js so if you store that file on any other directory level then it will throw that error.
Let's say the manifest-json file is stored in public/app/manifest-json.js, then for a file located in public/app/css/app.css you would use:
<link rel="stylesheet" href="{{ mix('css/app.css', 'app') }}">
The mix()-helper function allows for a second argument, the directory of the manifest file. Just specify it there and it will use the correct manifest file.
i have same problem as questioner: manifest does not exist for solving it what i have done is ran 2 commands as following:
npm install
and then
npm run dev
and the error is solved now. yippi.
In shared hosts and laravel 5.6 tested:
after doing standard levels such as explained here;
two levels needed:
in app/Providers/AppServiceProvider.php:
$this->app->bind('path.public', function() {
return realpath(base_path().'/../public_html');
});
and in public_html file make .htaccess file with content:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 /index.php
</IfModule>
source: here
this file most change for some situations.
that's all and solved my problem
I had the same issue with a Laravel package, its assets were not published:
This solved the issue for me:
php artisan vendor:publish --tag=telescope-assets --force
Sources:
https://github.com/laravel/telescope/issues/136
https://github.com/laravel/telescope/issues/250
There are 3 ways to solve it, I summarize what the colleagues said above:
The problem is because, you are using mix() in the views.
<link rel="stylesheet" href="{{ mix('dist/css/app.css') }}">
solution 1
change it to this.
<link rel="stylesheet" href="{{ asset('dist/css/app.css') }}">
solution 2
If you don't have root access:
Modify the App\Providers\AppServiceProvider file and add the following to the boot() method.
$this->app->bind('path.public', function() {
return base_path().'/../public_html';
});
solution 3
if you have root access run:
npm install & npm run dev
try the following commands:
npm install
npm run dev
I have same exception after deployment laravel project to (shared) server when trying to reach the login and register page. It works fine on local machine.
I kept the file and folder structure the same as on my local environment (all files that our in the public folder locally are in the public_html folder on the server).
The solution mentioned above seems to work. Adapted to my file and folder structure I added the following code to AppServiceProvider file and inside boot() method.
$this->app->bind('path.public', function() {
return realpath(base_path().'/public_html');
});
The only issue now is that the CSS of the login, register and dashboard page is messed up. I'm totally new to Livewire, I have no clue how to fix that.
You should run this commands to install npm dependencies and make your frontend files:
$ npm install
$ npm run dev //or production
Now you're done and you can run your laravel project:
$ php artisan serve
In a shared hosting environment, Remove the mix e.g. {!! script(mix('js/manifest.js')) !!}
should be changed to
{!! script('js/manifest.js') !!}
This actually works for me
I got the same error
because when I run
npm install
npm run dev
I got some error.
It was fixed when I updated my nodejs version.
I'm just posting maybe someone would need it.
For me it's worked when I changed in my blade file css and js pointed path. As bellow:
In my blade was this:
<link rel="stylesheet" href="{{ mix('dist/css/app.css') }}">
I changed the MIX to ASSET as:
<link rel="stylesheet" href="{{ asset('dist/css/app.css') }}">
Also the same on JS file to:
<script src="{{ asset('dist/js/app.js') }}"></script>
If it's the same thing for everybody, in my case laravel-mix seems to be not installed so without changing any files I just installed laravel-mix by running:
npm install laravel-mix#latest --save-dev
For bind your public path to public_html, in file index.php add this 3 lines:
$app->bind('path.public', function() {
return __DIR__;
});
This is work for me on shared hosting
Try to Add your public route to your app/Providers/AppServiceProvider.php
public function register()
{
$this->app->bind('path.public',function(){
return'/home/hosting-name-folder/public_html';
});
}
Directory Structure like this
--- public
--- app
--css
--app.css
--js
--app.js
Import css js in laravel blade file like this
<link rel="stylesheet" href="{{ asset('app/css/app.css') }}">
<script src="{{ asset('app/js/app.js') }}" type="text/javascript"></script>
If you are having this issue with Laravel Nova or telescope then perhaps you are really missing mix-manifest file. You should have that file inside public/vendor/toolname/
Where toolname can be Nova or Telescope. If you have that folder, you should go ahead and put in your server otherwise you will first have to publish the assets & then put it on server.
I change resources/layouts/guest.blade.php and resources/layouts/app.blade.php
<!-- Styles -->
<link rel="stylesheet" href="{{asset('css')}}/app.css">
<!-- Scripts -->
<script src="{{asset('css')}}js/app.js"></script>
and resources/css and resources/js copy my public folder
The Mix manifest does not exist.
You can solve this problem by updating the node version.
actually when you run command npm run dev,
show the error message "Error: You are using an unsupported version of Node. Please update to at least Node v12.14"
so easily you can fix it by updating the node js version
Thanks
if your previous setup is correct.but you are looking this type of error it shows The Mix manifest does not exist. then write these command .
npm ci
npm run dev
I resolved my problem by this command :
npm install
npm run dev
Worked for me on a fresh install of Laravel 9 with Jetstream(using Laradock).
npm run install && npm run development
When running npm run dev the mix was not compiling the files and creating the mix-manifest.json
step1
npm install
npm run production
step 2
refresh by simply closing and opening the project
step 3
replace <link rel="stylesheet" href="{{ mix('css/app.css') }}">
with
<link rel="stylesheet" href="/css/app.css/">
Here you go!!!!!
I got the same problem when hosting on cpanel
just change from
{{ mix('backend/css/app.css') }}
Becomes
{{ asset('backend/css/app.css') }}
it's solve my problem.
don't forget to upvote if this answer help u
There are a lot of answers to these questions, I am posting this question just in case if any miss these points.
Method: 1
Make sure to check the .gitignore file. sometimes it's listed there and doesn't make the file be pushed to git repo
Method: 2
Add this code in webpack.mix.js so you will exactly know where it's placing the mix-manifist.json file
mix.webpackConfig({
output: {
path: __dirname + "/public"
}
});
I had the issue on a shared host, where I was not able to run npm commands. Then I used the simplest way. In the /vendor/laravel/.../Foundation/Mix.php replace
i$manifests[$manifestPath] = json_decode(file_get_contents($manifestPath), true);
to
$manifests[$manifestPath] = json_decode(file_get_contents('https://your-domain.com/mix-manifest.json'), true);
Not recommended, but it works. You can use it as your last try.
Faced the same problem on both Windows and Ubuntu. Solved it on Ubuntu (and I presume the solution is simillar in Windows). The problem was due to the fact that my installed npm version was too old.
The solution for me was the following. I installed nvm (NodeVersionManager -version 0.39.1) which allowed me to switch to the latest stable version of node (v16.14.0) and then install npm 8.5.0.
Detailed steps:
Linux bash terminal commands:
touch ~/.bash_profile ~/.bashrc ~/.zshrc ~/.profile
sudo apt install curl
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
logout and login Ubuntu user
nvm --version
nvm ls-remote
nvm install 16.14.0
node --version
...then inside the laravel project:
npm ci
npm install -g npm#8.5.0
npm audit fix
npm run dev
Try out this one!!
<script src="{{ asset('js/app.js') }}" defer></script>
It works for me
I found new solution
The problem is mix manifest right?
So just redirect to the mix manifest feature. for example, you have:
{{ style(mix('css/backend.css')) }}
just change your code into
{{ style('css/backend.css') }}
it works for me

How to deploy React/Laravel project?

I use Laravel framework as Restful API server, and React as SPA client render and for routing i have used react create app kit, I build React project. I get app.js and app.css files by type npm run build.
How to use this file with Laravel?
How use react routing?
How to deploy it correctly?
I can answer your questions and have an example.
Basically, to use Laravel as an API backend for a React (or JS) Single-Page application:
setup a Laravel project - it's the backend, so setup it and the routes you want
1.a Suggestion Make your URLs for the SPI separate/distinct from normal URLs your Laravel app itself might use for page requests or other things (such as "/api/...").
1.b Laravel (5+ or so, my example is 5.1) comes packaged with a Gulp/build tool called "Elixir". It's setup to look for things like scripts files and views in the resources/... directory, so I suggest putting your scripts in some place like resources/assets/scripts/app.js or something.
1.c (Build Process) Assuming you put your React scripts in resources/assets/script, then when you run "gulp" and the Elixir task runs for building the app, it will put the bundled, app.js file into public/js/app.js -- Laravel views by default think of the public/ directory as their root directory, so you can reference that built file in your index page as "js/app.js".
1.d If Gulp or Elixir are unfamiliar to you, I encourage you to give this page a read for an overview:
https://laravel.com/docs/5.1/elixir
setup the Routes for Laravel, your Index page and the API stuff. I suggest routing '/' and all NON-API (or known) routes to just make the Index page View, where we'll load the app.js ReactJS application file.
2.a It's worth noting that in my example, currently, I have not implemented the React Router, so I'm leaving all React routes alone for the moment. I'm assuming this is something you know since your questions seems to be "how to make the Backend be Laravel".
Route::get('/', function () { return View::make('pages.index'); });
Route::group(['prefix' => 'api'], function () {
Route::get('tasks', 'TodosController#index');
});
2.b Setup the Routes to map requests to controller actions, where you can customize your response. For example, you can respond with JSON for a JSON API:
TodosController#index
$current_tasks = array(
array("id" => "00001", "task" => "Wake up", "complete" => true),
array("id" => "00002", "task" => "Eat breakfast with coffee power", "complete" => true),
array("id" => "00003", "task" => "Go to laptop", "complete" => true),
array("id" => "00004", "task" => "Finish React + Laravel Example app", "complete" => false),
array("id" => "00005", "task" => "Respond on StackOverflow", "complete" => false)
);
return response()->json($current_tasks);
As far as deployment goes, you'll probably need to build the code (my example does) and load the built version of the code into your production Index page or wherever. You'll also deploy it overall as a laravel app -- you want Laravel seeing the Routes first externally and want React to handle it's own URLs and routes. This way, say you expand the SPA but want the same backend, you just add routes to your Laravel app as exceptions/overrides in the routes file.
resources/pages/index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>BLaravel 5.1 + ReactJS Single-Page App</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<link rel="stylesheet" href="css/app.css" />
<!-- BACKUP SCRIPT CNDS, for React -->
<!-- <script src="https://unpkg.com/react#15/dist/react.js"></script> -->
<!-- <script src="https://unpkg.com/react-dom#15/dist/react-dom.js"></script> -->
</head>
<body>
<!-- Container for React App -->
<div class="container" id="react-app-container"></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Because there's (as far as I know) no Plnkr for this sort of thing, I made a local development version of Laravel + React to illustrate my way of making the kind of app you seem to be asking for. It's currently hosted on my GitHub account, so feel free to clone it and follow the README and use it if it helps, or ask for edits/help/clarification.
https://github.com/b-malone/Laravel5-ReactJS-Boilerplate.git
Build/Setup Commands (Reference)
git clone ... [TEST/] && cd into [TEST/]
composer install
npm install
cp .env.example .env
gulp
php artisan serve
visit http://localhost:8000
Please find the steps to run app in your local machine
Step 1:
Download the code from git
Step 2:
Composer install
Step 3:
Npm install
Please do following steps if you face - cross-env NODE_ENV=development webpack --progress --hide-modules --
You need to make cross-env working globally instead of having it in the project.
1) remove node_modules folder
2) run npm install --global cross-env
3) remove "cross-env": "^5.0.1", from package.json file devDependencies section. Actually, you can skip this step and keep package.json intact. If you prefer.
4) run npm install --no-bin-links
5) run npm run dev
Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command
Step 4:
Npm run dev
Step 5:
Php artisan serve
we can simplify our task by this bash script.ssh
#!/bin/bash
#install updates
sudo apt-get update
sudo apt-get upgrade
#install nginx
sudo apt-get install nginx
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash
#install nodejs
sudo apt-get install -y nodejs
#status of install ndoe and nginx
node -v
sudo service nginx status
#clone repo of project in server
git clone https://github.com/your_new_project.git
cd your_new_project
npm run build
#(first time,it downlod lib,and files )
npm run build
#(second time,he build and run it)
cd build/
ls
ls static/
#now tell nginx server (listen :80/ root :path of build folder/ location :index.html)
Create a project file
sudo nano /etc/nginx/sites-available/react_counter
server {
server_name your_IP domain.com www.domain.com;
root /home/username/React-counter-app/build;
index index.html index.htm;
location / {
try_files $uri /index.html =404;
}
}
server_name put your IP address
root we use this to give the server the application located in the disk
index The main file
Enable the file by linking to the sites-enabled dir
sudo ln -s /etc/nginx/sites-available/react_counter /etc/nginx/sites-enabled
Test NGINX config
$ sudo nginx -t
Restart Nginx Server
$ sudo systemctl restart nginx
Open your browser and go to http://youripaddress
Thanks for reading. #syedasadrazadevops

One shared vendor with two projects

I'm working on 2 applications right now. The first one is a CMS, and the second is a shop. I want to move my vendor one level above and the share it between projects.
So my structure will be something like this:
project1/
project2/
shared_vendor/
I read about this.
I have changed the app/autoload.php loader variable from:
$loader = require __DIR__.'/../vendor/autoload.php';
to:
$loader = require __DIR__.'/../../vendor/autoload.php';
And I have also changed vendor-dir in my composer.json from:
"config": {
"bin-dir": "bin",
"vendor-dir": "vendor"
},
to:
"config": {
"bin-dir": "bin",
"vendor-dir": "/../vendor"
},
And after this I'm getting this error:
ClassNotFoundException in AppKernel.php line 20: Attempted to load
class "CmsUserBundle" from namespace "Cms\UserBundle".
Did you forget a "use" statement for another namespace?
What am I doing wrong? Did I forget to change something?
Thanks in advance.
Composer works on a per project basis.
One project - one vendor folder. Not, two projects and one "shared" vendor folder.
We had the "shared" vendor folder approach with PEAR long enough and it simply didn't work out. Managing different project requirements with a global vendor folder is a pain, because every project has different requirements.
Anyway...
if you like the "shared vendor folder" setup, i would suggest to create something like a "wrapper" or "super" project, which acts as container repository for the two other projects. The wrapper project will contain the composer.json file with the requirements for both(!) projects. That means that you are working against the same set of dependencies in both sub-projects.
This allows to define requirements for both sub-projects (cms and shop)
in the "wrapper" repo. Basically, i'm suggesting the following structure:
|-container-project
+-CMS
|-src
+-tests
+-Shop
|-src
+-tests
+-vendors // contains dependencies for both projects (CMS + Shop)
|-composer.json // define requirements for both projects
This setup allows to introduce composer.json files for the subprojects, too.
You just have to transfer the requirements from the composer.json file of the super-project to the composer.json file of a subproject.
Now, it's also possible to tweak the autoloading behavior of the sub-projects by registering autoloaders in a specific order.
For Laravel 5, 6 and 7+
After adding the new vendor folder config:
...
"config": {
...,
"vendor-dir": "../vendor"
},
...
Then run composer update
Then you need to change two files:
For your app: public/index.php
require __DIR__.'/../../vendor/autoload.php';
Your artisan command in the root folder: artisan
require __DIR__.'/../vendor/autoload.php';
Package auto-discovery in Illuminate\Foundation\PackageManifest:
$this->vendorPath = $basePath.'/../vendor'; //Change this line in constructor
and rerun
php artisan package:discover --ansi
I know this is an old question but I run into the same problem. I'm using Laravel 7 and I solved the problem with the following method.
I wrote a shellscript (my-vendor.sh) at the root of my project with the following code :
#!/bin/bash
MY_VENDOR_DIRECTORY=my-vendor
VENDOR_DIRECTORY=vendor
if [ ! -d "$MY_VENDOR_DIRECTORY" ]
then
echo "Le dossier $MY_VENDOR_DIRECTORY n'existe pas : on le crée."
mkdir "$MY_VENDOR_DIRECTORY"
else
echo "Le dossier $MY_VENDOR_DIRECTORY existe : on le vide."
rm -rf "$MY_VENDOR_DIRECTORY/*"
fi
echo "Copie des fichiers autoload généré depuis $VENDOR_DIRECTORY vers $MY_VENDOR_DIRECTORY."
cp "$VENDOR_DIRECTORY/autoload.php" "$MY_VENDOR_DIRECTORY"
cp -R "$VENDOR_DIRECTORY/composer" "$MY_VENDOR_DIRECTORY"
cd "$MY_VENDOR_DIRECTORY/composer"
echo "Remplacement de 'require \$file' par \str_replace(\"$MY_VENDOR_DIRECTORY\/composer\/..\", \"vendor\", \$file)"
sed -i "s/require \$file/require \\str_replace('$MY_VENDOR_DIRECTORY\/composer\/..', 'vendor', \$file)/" autoload_real.php
echo "Remplacement de 'include \$file' par \str_replace(\"$MY_VENDOR_DIRECTORY\/composer\/..\", \"vendor\", \$file) "
sed -i "s/include \$file/require \\str_replace('$MY_VENDOR_DIRECTORY\/composer\/..', 'vendor', \$file)/" ClassLoader.php
Then, I replace the following code in public/index.php :
require __DIR__.'/../vendor/autoload.php' => by require __DIR__.'/../my-vendor/autoload.php';
After that, I add my-vendor.sh command in the post-autoload-dump scripts.
I made this modifications in my two projects, launch composer dump-autoload and it work like a charm :)
A link to the gist : https://gist.github.com/flibidi67/7c2cfdc1ff1b977b48204be0bee5eb76
Hope this can help someone else ;)
Based on your requirements and if the only thing you need/want to share between your multiple projects is the vendor directory, you could just create symlinks in each project except whatever the main one which already has the the vendor directory.
For example:
cd /var/www/SiteA
composer install
# git clone new project into /var/www/SiteB
cd ../SiteB
# If vendor directory is already there, delete it: rm -rf vendor
# create symlink to Site A's vendor directory
ln -s /var/www/SiteA/vendor
Unless you know for sure that all projects are definitely going to need exactly the same versions of your dependancies, this maybe not a good plan.

Categories