简体   繁体   English

如何让Webpack,Wordpress和BrowserSync协同工作?

[英]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. 如果我代理myserver.dev热重装404s。 Changing the publicPath does nothing. 更改publicPath什么都不做。 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. 我将网址附加到webpack-hot-middleware / client,它修复了路径,但是hmr文件在控制台中没有信息时出现“GET”错误。 Hot reloading works fine if I keep it HTML and disregard any php/MAMP. 如果我保持HTML并忽略任何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 - 用于REST API的Wordpress
- React for views and ui - 对视图和ui做出反应
- MAMP for localhost & MySQL - 用于localhost和MySQL的MAMP
- BrowserSync for testing across devices - BrowserSync,用于跨设备进行测试
- Webpack for compiling and hot reloading - Webpack用于编译和热重新加载

This is the boilerplate I used: https://github.com/Browsersync/recipes/tree/master/recipes/webpack.react-hot-loader 这是我使用的样板: https //github.com/Browsersync/recipes/tree/master/recipes/webpack.react-hot-loader

Theme Directory Structure: 主题目录结构:
-/inc - / INC
-/src - / src目录
--/components - /组件
--/containers - /容器
--/styles - /风格
--app.js --app.js
-bundle.js -bundle.js
-functions.php -functions.php
-index.php -index.php
-package.json -package.json
-server.js -server.js
-style.css -style.css
-webpack.config.js -webpack.config.js

I've tried a million configurations so I gutted the code below for simplicities sake. 我已经尝试了一百万种配置,所以为了简单起见,我为了下面的代码而掏空了这些代码。

webpack.config.js: 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: 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: 的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 . 到2018年中期,新版本的Webpack和BrowserSync for Wordpress可能已经发生了变化 - 但我有一个非常简单,现代的Webpack和BrowserSync配方,适用于Word,它可以为JS,CSS PHP提供实时重载 This uses React, but isn't specific to a React setup, just ES6 module importing/exporting. 这使用React,但不是特定于React设置,只是ES6模块导入/导出。

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: 的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 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 Postcss.config.js

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

.babelrc .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. 其他建议包括Prettier on precommit(使用Lint-Staged和Husky)用于所有JS项目的代码格式化,适当的.gitignore用法(适用于此处)和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. 好吧,不是一个精心设计的答案,但我在我的Gutenberg Boilerplate中有一个非常基本的Webpack设置,可以帮助你开始使用WordPress中的ESNext,React,Webpack。

Check out the Block #02 and it's configuration . 查看Block#02及其配置

I wanted to answer this for you with a link: https://css-tricks.com/combine-webpack-gulp-4/ 我想通过链接为您解答这个问题: 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. 它确实使用gulp,但你可以简单地将其从配置中删除并稍微破解。 The basics of the setup are all there though. 尽管如此,设置的基础知识仍然存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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