首页 > 解决方案 > 在进行 Webpack-Dev-Server HMR 时在 WordPress 中排队脚本

问题描述

我正在努力成为一个优秀的 WordPress 公民,并以正确的方式包含我的 JavaScript,通过wp_enqueue_scripts在我的functions.php.

但是,这样做我不会通过webpack-dev-server进行热模块重新加载(hmr)工作。

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

标签: wordpresswebpackwebpack-hmr

解决方案


这里没有反应,所以我不得不自己寻找答案。这里是。

我没有得到的是如何使webpack-dev-server仅在内存中可用的bundle.js文件在.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()]
};

问题是:虽然我通过我的 MAMP-server 代理 dev-sever,但在文件下运行http://wordpress:8888build.jswebpack -dev-server不能在原始 url下http://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所以现在只需在I can WordPress make 中添加一行来查找bundle.js文件,webpack-dev-server将它放在其中。如果缺少此行,它将bundle.js从主题目录的根目录加载文件。

我的wp-config.php(提取)

define('WP_ENVIRONMENT', 'development');

推荐阅读