Webpack dev server php

Using the Webpack dev server with a PHP application

Since I first answered this question I’ve started using a different solution.

With the new solution you make requests directly to an nginx/apache web server. The web server works as a proxy and redirects requests to either webpack-dev-server or the php application. The php application exposes all it’s endpoints under /api/ (see untested example configurations below, where localhost:8080 refers to webpack-dev-server).

Apache config (http://php-application refers to a separate VirtualHost, not shown here)

 ServerName my-website.dev ProxyPass / http://localhost:8080/ ProxyPassReverse / http://localhost:8080/ ProxyPassMatch ^\/api\/.+$ http://php-application/ ProxyPassReverse / http://php-application/ 

Nginx config (PHP7.1)

— Old answer —

I know you made it work, but I came across this post when I had this problem myself and, after solving it, wanted to share my solution.

I’m not using Laravel, but have a PHP backend on an apache server. I only had to make two changes in webpack.config.js to make webpack dev server work:

To this (note: http://localhost:8080 is the url to the webpack-dev-server)

publicPath: "http://localhost:8080//" 

And add some proxy settings to forward requests to the php backend

Notice that the path property is a regex that matches everything. This will cause all requests to be forwarded to the php backend. You might have to change the regex if you want the frontend to handle some requests.

The webpack dev server documentation also says that you have to change your script tags src attribute to http://localhost:8080// , but this is only necessary for me if I want to access the app from its old (apache) url in stead of localhost:8080 when using the —inline flag.

To make hot module replacement work with react:

  • Install react-hot-loader: npm install —save-dev react-hot-loader
  • Add the loader to your webpack.config.js along with your other loaders as react-hot

Now all you have to do is run webpack-dev-server —inline —hot and, hopefully, you are golden.

Solution 2

I had similar problem: On my desctop i have PHP server runing with Open Server and also Webpack Vue app. I wanted to have access to API with AJAX from my Vue app. So whis is my solution:

Create local domain (i don’t like ‘localhost’, so i created loc-team.test) with Open Server (you can use XAMPP, or e.g.). Now i have access to http://loc-team.test/ajax.php from browser, but i don’t have AJAX access to this URL from my Webpack dev server (http://loc-team.test:8081), because of Access-Control-Allow-Origin / CORS.

Add proxy to your devServer In webpack dev configuration include this props:

So in my Vue app i can make AJAX request to loc-team.test/api/ajax.php, and because of pathRewrite i will get answer from loc-team.test/ajax.php. Also i have no problem with sessions.

Читайте также:  Generate background page html

Источник

Using the Webpack dev server with a PHP application

Since I first answered this question I’ve started using a different solution.

With the new solution you make requests directly to an nginx/apache web server. The web server works as a proxy and redirects requests to either webpack-dev-server or the php application. The php application exposes all it’s endpoints under /api/ (see untested example configurations below, where localhost:8080 refers to webpack-dev-server).

Apache config (http://php-application refers to a separate VirtualHost, not shown here)

80> ServerName my-website.dev ProxyPass / http://localhost:8080/ ProxyPassReverse / http://localhost:8080/ ProxyPassMatch ^\/api\/.+$ http://php-application/ ProxyPassReverse / http://php-application/

Nginx config (PHP7.1)

server < listen 80; server_name my-website.dev; root /path/to/backend/public; index index.php index.html; location / < proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://localhost:8080; > location ~ ^/api/.+$ < try_files /index.php =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/run/php/php7.1-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; >>

— Old answer —

I know you made it work, but I came across this post when I had this problem myself and, after solving it, wanted to share my solution.

I’m not using Laravel, but have a PHP backend on an apache server. I only had to make two changes in webpack.config.js to make webpack dev server work:

To this (note: http://localhost:8080 is the url to the webpack-dev-server)

publicPath: "http://localhost:8080//"

And add some proxy settings to forward requests to the php backend

devServer: < proxy: [ < path: /./, target: "http://" > ]>

Notice that the path property is a regex that matches everything. This will cause all requests to be forwarded to the php backend. You might have to change the regex if you want the frontend to handle some requests.

The webpack dev server documentation also says that you have to change your script tags src attribute to http://localhost:8080// , but this is only necessary for me if I want to access the app from its old (apache) url in stead of localhost:8080 when using the —inline flag.

To make hot module replacement work with react:

  • Install react-hot-loader: npm install —save-dev react-hot-loader
  • Add the loader to your webpack.config.js along with your other loaders as react-hot

Now all you have to do is run webpack-dev-server —inline —hot and, hopefully, you are golden.

Источник

Using the Webpack dev server with a PHP application

Has anybody had an experience with installation webpack dev server on Laravel 5+ (5.1 in my case)? I’m going to use my laravel PHP backend with the ReactJS frontend and I would like to have webpack dev server on my dev env. But I’m confused with a lot of configs in NodeJS (I’m specialized in PHP backend). Is it generally possible to combine webpack dev server with PHP application? I want my env to work both ways: on my apache server (for backend debugging/development) and on NodeJS server (for frontend debugging/development). Do I need to have some middleware, resolving specific port for webpack? How in general NodeJS server will load my PHP scripts? . or apache web server would load page than NodeJS would push notifications to frontend?

Читайте также:  Javascript date last day

With a lot of headache, but yes. You just need to load your assets from NodeJS server (not from PHP application). Then, the rest of Webpack Dev Server documentation is applicable.

2 Answers 2

— New answer —

Since I first answered this question I’ve started using a different solution.

With the new solution you make requests directly to an nginx/apache web server. The web server works as a proxy and redirects requests to either webpack-dev-server or the php application. The php application exposes all it’s endpoints under /api/ (see untested example configurations below, where localhost:8080 refers to webpack-dev-server).

Apache config (http://php-application refers to a separate VirtualHost, not shown here)

 ServerName my-website.dev ProxyPass / http://localhost:8080/ ProxyPassReverse / http://localhost:8080/ ProxyPassMatch ^\/api\/.+$ http://php-application/ ProxyPassReverse / http://php-application/ 

Nginx config (PHP7.1)

— Old answer —

I know you made it work, but I came across this post when I had this problem myself and, after solving it, wanted to share my solution.

I’m not using Laravel, but have a PHP backend on an apache server. I only had to make two changes in webpack.config.js to make webpack dev server work:

To this (note: http://localhost:8080 is the url to the webpack-dev-server)

publicPath: "http://localhost:8080//" 

And add some proxy settings to forward requests to the php backend

Notice that the path property is a regex that matches everything. This will cause all requests to be forwarded to the php backend. You might have to change the regex if you want the frontend to handle some requests.

The webpack dev server documentation also says that you have to change your script tags src attribute to http://localhost:8080// , but this is only necessary for me if I want to access the app from its old (apache) url in stead of localhost:8080 when using the —inline flag.

To make hot module replacement work with react:

  • Install react-hot-loader: npm install —save-dev react-hot-loader
  • Add the loader to your webpack.config.js along with your other loaders as react-hot

Now all you have to do is run webpack-dev-server —inline —hot and, hopefully, you are golden.

Источник

Как завести webpack-dev-server с livereload frontend и php на backend?

Имеется проект на Svelte.js и php в качества backend. так уже сложились обстоятельства.
Проект собирается webpack на основе предлагаемого стандартного шаблона svelte для webpack.
PHP в проекте пока лежит статикой.

Всё отлично собирается и даже с livereload взлетает, все прекрасно.
За исключением того что php под webpack-dev-server не заводится.

На компьютере установлен php 7.
Подозреваю, что нужен либо какой-то доп пакет, либо настройка webpack-dev-server.
Но гугл и яндекс пока не дают ответа на вопрос, чего же не хватает в моём конфиге, что бы без iis и apache (и иже с ними) было достаточно `npm run dev` для запуска проекта с поддержка php backend-а и livereload на клиенте.

resolve: < alias: < svelte: path.resolve('node_modules', 'svelte') >, extensions: ['.mjs', '.js', '.svelte'], mainFields: ['svelte', 'browser', 'module', 'main'] >, output: < path: __dirname + '/public', filename: '[name].js', chunkFilename: '[name].[id].js' >, module: < rules: [ < test: /\.svelte$/, exclude: /node_modules/, use: < loader: 'svelte-loader', options: < emitCss: true, hotReload: true, dev: true >> >, < test: /\.css$/, use: [ prod ? MiniCssExtractPlugin.loader : 'style-loader', 'css-loader' ] >] >, mode, plugins: [ new MiniCssExtractPlugin(< filename: '[name].css' >) ], devtool: prod ? false: 'source-map'

Известно что начиная с 5.4 в php появился встроенный сервер, который можно поднять командой php -S localhost:8000
Однако, я не могу это как-то связать в webpack и livereload

Читайте также:  Single page application php

Средний 2 комментария

Источник

How to get webpack-dev-server working with an existing app?

In my setup, we develop on our local machines and then rsync our code to a vagrant box. I got this working by running webpack -w and an rsync daemon together — webpack builds the files and then rsync immediately picks up the changes and uploads them. However, this won’t work with live/hot-reloading. So what I was hoping to do was to swap out these two lines in my HTML:

And then live/hot reloading would magically work. I can’t run my whole app under the webpack-dev-server because nginx still needs to serve up the rest of the PHP app, including some non-webpacked assets. Right now the the above 2 lines of HTML are generated by this function:

function($chunkName) < static $stats; if($stats === null) < $stats = WxJson::loadFile(WX::$path.'/webpack.stats.json'); >$paths = WXU::array_get($stats,['assetsByChunkName',$chunkName],false); if($paths === false) < throw new \Exception("webpack asset not found: $chunkName"); >$html = []; foreach((array)$paths as $p) < $ext = WXU::GetFileExt($p); switch($ext) < case 'js': $html[] = WXU::html_tag('script',['src'=>WXU::join_path($stats['publicPath'],$p),'charset'=>'utf-8'],''); break; case 'css': $html[] = WXU::html_tag('link',['href'=>WXU::join_path($stats['publicPath'],$p),'rel'=>'stylesheet','type'=>'text/css; charset=utf-8'],null); break; > > return implode(PHP_EOL, $html); > 
  1. Can I get hot-loading to work without changing our web URL? i.e., can I keep the URL the same but link to a bundle served by webpack-dev-server rather than visiting webpack-dev-server and have it proxy the rest of our site?
  2. Is there another way for me to retrieve the bundle name in PHP rather than trying to parse this stats file which doesn’t exist when using the webpack-dev-server?

Here’s my webpack.config.js if you need to see it.

'webpack-dev-server/client?http://localhost:5584/assets/', 'webpack/hot/only-dev-server', 

And new webpack.HotModuleReplacementPlugin() in my webpack.config.json and compile it (with webpack not webpack-dev-server ) then I see this in my Chrome dev tools:

GET http://localhost:5584/assets/info?t=1450478928633 net::ERR_CONNECTION_REFUSEDAbstractXHRObject._start @ abstract-xhr.js:128(anonymous function) @ abstract-xhr.js:21 [WDS] Disconnected! 

Which is good. It looks like the bundle does contain the necessary code, now I just have to figure out how get the URL for the bundle from PHP and fix the CORS issue.

Источник

Оцените статью