简体   繁体   中英

How to get Webpack, Wordpress, and BrowserSync to work together?

I've been at it for about a week now and I haven't been able to get the three to work together. I'll be eternally grateful if anyone can help me with this, I've wasted so many hours.

The issue:
If I proxy myserver.dev hot reloading 404s. Changing the publicPath does nothing. I attach the url to webpack-hot-middleware/client, it fixes the path, but the hmr file ends up having a "GET" error in console with no info. Hot reloading works fine if I keep it HTML and disregard any php/MAMP. I'm overall really confused and I'm probably missing a simple concept.

What I'm trying to get to work together:
- Wordpress for its REST API
- React for views and ui
- MAMP for localhost & MySQL
- BrowserSync for testing across devices
- Webpack for compiling and hot reloading

This is the boilerplate I used: https://github.com/Browsersync/recipes/tree/master/recipes/webpack.react-hot-loader

Theme Directory Structure:
-/inc
-/src
--/components
--/containers
--/styles
--app.js
-bundle.js
-functions.php
-index.php
-package.json
-server.js
-style.css
-webpack.config.js

I've tried a million configurations so I gutted the code below for simplicities sake.

webpack.config.js:

var webpack = require('webpack');
var path = require('path');

module.exports = {
  context: path.join(__dirname, 'src'),

  entry: [
    'webpack/hot/dev-server',
    'webpack-hot-middleware/client',
    './app'
  ],

  output: {
    path: __dirname,
    publicPath: __dirname,
    filename: 'bundle.js'
  },

  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],

  module: {
    loaders: [
      { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] }
    ]
  }
};

server.js:

/**
 * Require Browsersync along with webpack and middleware for it
 */
var browserSync = require('browser-sync');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');

/**
 * Require ./webpack.config.js and make a bundler from it
 */
var webpackConfig = require('./webpack.config');
var bundler = webpack(webpackConfig);

/**
 * Run Browsersync and use middleware for Hot Module Replacement
 */
browserSync({
    proxy: {
      target: 'http://myserver.dev',
      middleware: [
        webpackDevMiddleware(bundler, {
          // IMPORTANT: dev middleware can't access config, so we should
          // provide publicPath by ourselves
          publicPath: webpackConfig.output.publicPath,

          // pretty colored output
          stats: { colors: true }

          // for other settings see
          // http://webpack.github.io/docs/webpack-dev-middleware.html
        }),

        // bundler should be the same as above
        webpackHotMiddleware(bundler)
      ]
    },

    // prevent opening a new window.
    open: false,

    // no need to watch '*.js' here, webpack will take care of it for us,
    // including full page reloads if HMR won't work
    files: [

    ]
});

package.json:

{
  "main": "server.js",
  "scripts": {
    "build": "webpack",
    "start": "node ."
  },
  "dependencies": {
    "babel-core": "^5.8.9",
    "babel-loader": "^5.3.2",
    "browser-sync": "^2.8.0",
    "react": "^0.13.3",
    "react-hot-loader": "^1.2.8",
    "webpack": "^1.10.5",
    "webpack-dev-middleware": "^1.2.0",
    "webpack-hot-middleware": "^1.1.0"
  }
}

Things may have changed with new version of Webpack and BrowserSync for Wordpress by mid-2018 – but I have a very simple, modern Webpack and BrowserSync recipe for Wordpress that has live reload for JS, CSS, and PHP . This uses React, but isn't specific to a React setup, just ES6 module importing/exporting.

Folder structure:

theme
⊢⊸ api
  ⊢⊸ models
  ⊢⊸ controllers
  ⊢⊸  index.php
⊢⊸ frontend
  ⊢⊸ src
    ⊢⊸ App.js
    ⊢⊸ App.css
    ⊢⊸ index.js
  ⊢⊸ .babelrc
  ⊢⊸ package.json
  ⊢⊸ postcss.config.js
  ⊢⊸ webpack.config.js
  ⊢⊸ yarn.lock
⊢⊸ main.js
⊢⊸ functions.php
⊢⊸ index.php
⊢⊸ style.css

Package.json:

"scripts": {
  "start": "webpack --mode development --watch",
  "build": "webpack --mode production"
},
"devDependencies": {
  "autoprefixer": "^8.5.0",
  "babel-core": "^6.26.3",
  "babel-loader": "^7.1.4",
  "babel-preset-env": "^1.7.0",
  "babel-preset-react": "^6.24.1",
  "browser-sync": "^2.24.4",
  "browser-sync-webpack-plugin": "^2.2.2",
  "css-loader": "^0.28.11",
  "extract-text-webpack-plugin": "^4.0.0-beta.0",
  "postcss-loader": "^2.1.5",
  "react": "^16.4.0",
  "react-dom": "^16.4.0",
  "style-loader": "^0.21.0",
  "webpack": "^4.8.3",
  "webpack-cli": "^2.1.3",
  "webpack-dev-server": "^3.1.4"
}

Webpack.config.json

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');

module.exports = {
  entry: { main: './src/index.js' },
  output: {
    path: path.resolve(__dirname, './../'),
    filename: 'main.js'
  },
  devtool: 'inline-source-map',
  devServer: {
    openPage: '',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract(
          {
            fallback: 'style-loader',
            use: ['css-loader', 'postcss-loader']
          }
        )
      }
    ]
  },
  plugins: [ 
    new ExtractTextPlugin({filename: 'style.css'}),
    new BrowserSyncPlugin({
      files: [
        './../',
        './../api/**/*.php',
        './../api/*.php',
        './', 
        '!./node_modules',
        '!./yarn-error.log',
        '!./package.json',
        '!./style.css.map',
        '!./app.js.map'
      ],
      reloadDelay: 0
    })
  ]
};

Postcss.config.js

module.exports = {
  plugins: [
    require('autoprefixer')
  ]
}

.babelrc

{
  "presets": ["env", "react"]
}

Other recommendations include Prettier on precommit (using Lint-Staged and Husky) for code formatting on all JS projects, appropriate .gitignore usage where applicable here, and ACF Builder for WP devs.

Well, not exactly a well-crafted answer but I have a very basic Webpack setup in my Gutenberg Boilerplate that will help you get started with ESNext, React, Webpack in WordPress.

Check out the Block #02 and it's configuration .

I wanted to answer this for you with a link: https://css-tricks.com/combine-webpack-gulp-4/

This article goes through everything needed to solve the problem. Works great for me. It does use gulp, but you could simply strip that out of the config and hack around a bit. The basics of the setup are all there though.

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