在执行 Webpack-Dev-Server HMR 时在 WordPress 中排队脚本

Enqueuing Script in WordPress while doing Webpack-Dev-Server HMR

我正在努力成为一名优秀的 WordPress 公民,并通过 functions.php.

中的 wp_enqueue_scripts 以正确的方式包括我的 JavaScript

但是这样做我无法通过 webpack-dev-server 热模块重新加载 (hmr) 工作。

任何人都可以给我提示或指出一些文档吗?

这里没有反应,只好自己找答案了。 在这里。

我没有得到的是如何制作 bundle.js 文件,webpack-dev-server 只在内存中提供,WordPress 使用 wp_enqueue_scriptsfunctions.php.

我的webpack.config.js(摘录)

const webpack = require('webpack');

module.exports = {
  entry: './src/entry.js',
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      }
    ]
  },
  devServer: {
    open: true,
    hot: true,
    publicPath: '/',
    proxy: {
      '/': {
        target: 'http://wordpress:8888/',
        changeOrigin: true
      }
    }
  },
  plugins: [new webpack.HotModuleReplacementPlugin()]
};

问题是:尽管我通过运行在 http://wordpress:8888 下的 MAMP 服务器代理开发服务器,但 webpack-dev 无法使用 build.js 文件-serverhttp://wordpress:8888/build.js 下但在原来的 url 下,即 http://localhost:8080/build.js.

一旦我得到 functions.php 中的条件语句就成功了。

我的functions.php(摘录)

<?php

// Load my JS
if (!defined('WP_ENVIRONMENT') || WP_ENVIRONMENT == "production") {

  function reactTheme_enque_scripts() {
    wp_enqueue_script(
      'react-theme-js',
      get_stylesheet_directory_uri() . '/bundle.js',
      [], // dependencies could go here
      time(), // version for caching
      true // loading it within footer
    );
  }

} else {

  function reactTheme_enque_scripts() {
    wp_enqueue_script(
      'react-theme-js',
      'http://localhost:8080' . '/bundle.js',
      [], // dependencies could go here
      time(), // version for caching
      true // loading it within footer
    );
  }

}

add_action('wp_enqueue_scripts', 'reactTheme_enque_scripts');

?>

所以现在只需在 wp-config.php 中添加一行,我就可以让 WordPress 查找 bundle.js 文件,其中 webpack-dev-server 是把它。 如果缺少这一行,它会从主题目录的根目录加载 bundle.js 文件。

我的wp-config.php(摘录)

define('WP_ENVIRONMENT', 'development');

我在这里为您发布了一个可能的答案:。这是 Wordpress 开发人员的 Webpack 设置。让我知道它是否有效。此致