简体   繁体   中英

Is there a way to achieve that Webpack Dev server proxy to wordpress properly?

I've seen some posts about it but with Webpack 5 maybe it can be done without the old problems. Necessity is basic; use webpack Dev server and HMR for WordPress development. Instead of reloading with browsersync.

Actually there is a post that guy named Christian wasted real time on this in the past. But I can't comment on that answer cuz I don't have the enough rep to comment...

WordPress redirecting to siteurl when accessed via webpack-dev-server proxy

Is there a way or is it worth to invest time on Dev server instead of browsersync? Any other solutions also accepted. Like if rollup or parcel has a similar option or snowpack maybe.

I will describe how I do it, there are many approaches to this problem, but what I have developed works for me, but it does not mean that it will be useful for you. Unfortunately it is based on browsersync but works on webpack 5;)

I'll start with the fact that I have a config folder with webpack.common.js, webpack.dev.js and webpack.prod.js files.

I will only describe the dev version - webpack.dev.js

const path = require('path');
const webpack = require('webpack');
const { merge } = require('webpack-merge');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const baseConfig = require('./webpack.common.js');

const buildMode =
  process.env.NODE_ENV === 'production' ? 'production' : 'development';
const { cssLoaders } = require('./util');

// Configure Dev Server
const configureDevServer = () => {
  return {
    writeToDisk: true,
    port: 3000,
  };
};

// Configure Css Loader
const configureCssLoader = () => {
  return {
    test: /\.(css|sass|scss)$/,
    use: ['style-loader', ...cssLoaders],
  };
};

module.exports = merge(baseConfig, {
  mode: 'development',
  target: 'web',
  devtool: 'inline-source-map',
  devServer: configureDevServer(),
  module: {
    rules: [configureCssLoader(buildMode)],
  },
  plugins: [
    new webpack.DefinePlugin({
      PRODUCTION: JSON.stringify(false),
    }),
    new BrowserSyncPlugin(
      {
        watchOptions: {
          aggregateTimeout: 200,
          poll: 1000,
        },
        proxy: 'http://localhost',
        files: [
          './wordpress/wp-content/themes/MY-TEMPLATE/**/*.php',
          './frontend/**/*.js',
          './frontend/**/*.scss',
        ],
      },
      {
        reload: false,
      }
    ),
  ],
});

I save files to the disk, in a specific place to my template, /wordpress/wp-content/themes/MY-TEMPLATE/assets/ Of course, the whole environment, the base, wordpress stands for a docker.

Each css and js file is saved in the form of filename: js/[name]-[hash].js for production version but for dev version filename: js/[name].js

Now the most important part is how to download a new file to wordpress every time the file changes, be it css or js.

I have some php functions in function.php

// wordpress/wp-content/themes/MY-TEMPLATE/functions.php

<?php

/**
 * Enqueue scripts and styles.
 */

require get_theme_file_path('/inc/mytemplate_styles_scripts.php');

In this file I have a function that downloads the appropriate files depending on whether we are in production or on localhost and puts them in the header if css, and if js then in the footer.

/**
 * adding css to head
 */
function kodywig_head_css()
{
  if ($_SERVER["SERVER_NAME"] !== 'localhost') {
    echo generateLinkOrScript('css', 'share');
  }
}
add_action('wp_head', 'kodywig_head_css', 0);

/**
 * adding js to footer
 */
function kodywig_head_js()
{
  if (is_singular()) {
    echo generateLinkOrScript('js', 'post');
  }
  echo generateLinkOrScript('js', 'share');
}
add_action('wp_footer', 'kodywig_head_js', 0);

/**
 * match file name
 */
function kodywig_matchFile($partOfName, $folder)
{
  $handler = get_template_directory() . '/assets/' . $folder;
  $openHandler = opendir($handler);
  while ($file = readdir($openHandler)) {
    if ($file !== '.' && $file !== '..') {
      if (preg_match("/^" . $partOfName . "(.*)" . $folder . "/i", $file, $name)) {
        return $name[0];
      }
    }
  }
  closedir($openHandler);
}

function generateLinkOrScript($type, $name)
{
  if ($type == 'css') {
    $nameLocal = $name . '-';
  } else {
    $nameLocal = $_SERVER["SERVER_NAME"] != 'localhost' ? $name : $name . '-';
  }

  if ($type == 'css') {
    $html = '<link href="' . get_template_directory_uri() . '/assets/' . $type . '/' . kodywig_matchFile($nameLocal, 'css') . '" rel="stylesheet">';
  } else {
    $html = '<script defer src="' . get_template_directory_uri() . '/assets/' . $type . '/' . kodywig_matchFile($name, 'js') . '"></script>';
  }
  return $html;
}

Each js, css change generates new files, which are uploaded to wordpress and the page is automatically reloaded.

If you work on windows, I recommend using wsl2 instead of docker. The compilation and refreshing of the page are extremely fast then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM