项目文件的热重载不会自动刷新浏览器

时间:2021-06-20 09:32:21

标签: javascript php css wordpress webpack

我正在尝试使用我的项目的捆绑资产进行热重载,但是当我对我的任何文件进行更改时,热重载并没有执行浏览器刷新。

F12 浏览器控制台没有显示任何东西,所以它没有被加载......?

functions.php

function workshop_01_theme() {
    wp_enqueue_script('workshop_01-js', get_theme_file_uri('/bundled-assets/scripts.bedc8565a6cb22e37037.js'), NULL, '1.0', true);
    wp_enqueue_style('worskshop_01-style', get_theme_file_uri('/bundled-assets/styles.bedc8565a6cb22e37037.css'));
}
add_action('wp_enqueue_scripts', 'workshop_01_theme');

package.json

{
  "name": "workshop_01",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "npm-run-all -p devFast buildWatch",
    "devFast": "webpack serve",
    "buildWatch": "webpack --watch",
    "build": "webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.14.5",
    "@babel/preset-env": "^7.14.5",
    "@babel/preset-react": "^7.14.5",
    "@glidejs/glide": "^3.4.1",
    "autoprefixer": "^10.2.6",
    "axios": "^0.21.1",
    "babel-loader": "^8.2.2",
    "clean-webpack-plugin": "^4.0.0-alpha.0",
    "css-loader": "^5.2.6",
    "cssnano": "^5.0.6",
    "fs-extra": "^10.0.0",
    "jquery": "^3.6.0",
    "mini-css-extract-plugin": "^1.6.0",
    "normalize.css": "^8.0.1",
    "npm-run-all": "^4.1.5",
    "postcss-color-function": "^4.1.0",
    "postcss-hexrgba": "^2.0.1",
    "postcss-import": "^14.0.2",
    "postcss-loader": "^6.1.0",
    "postcss-mixins": "^8.1.0",
    "postcss-nested": "^5.0.5",
    "postcss-simple-vars": "^6.0.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "style-loader": "^2.0.0",
    "webpack": "^5.38.1",
    "webpack-cli": "^4.7.2",
    "webpack-dev-server": "^3.11.2",
    "webpack-manifest-plugin": "^3.1.1"
  }
}

scripts.js

import "../css/styles.css"

// Allow new JS and CSS to load in browser without a traditional page refresh
if (module.hot) {
  module.hot.accept()
}

webpack.config.js

const currentTask = process.env.npm_lifecycle_event
const path = require("path")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const { CleanWebpackPlugin } = require("clean-webpack-plugin")
const { WebpackManifestPlugin } = require("webpack-manifest-plugin")
const fse = require("fs-extra")

const postCSSPlugins = [require("postcss-import"), require("postcss-mixins"), require("postcss-simple-vars"), require("postcss-nested"), require("postcss-hexrgba"), require("postcss-color-function"), require("autoprefixer")]

class RunAfterCompile {
  apply(compiler) {
    compiler.hooks.done.tap("Update functions.php", function () {
      // update functions php here
      const manifest = fse.readJsonSync("./bundled-assets/manifest.json")

      fse.readFile("./functions.php", "utf8", function (err, data) {
        if (err) {
          console.log(err)
        }

        const scriptsRegEx = new RegExp("/bundled-assets/scripts.+?'", "g")
        const vendorsRegEx = new RegExp("/bundled-assets/vendors.+?'", "g")
        const cssRegEx = new RegExp("/bundled-assets/styles.+?'", "g")

        let result = data.replace(scriptsRegEx, `/bundled-assets/${manifest["scripts.js"]}'`).replace(vendorsRegEx, `/bundled-assets/${manifest["vendors~scripts.js"]}'`).replace(cssRegEx, `/bundled-assets/${manifest["scripts.css"]}'`)

        fse.writeFile("./functions.php", result, "utf8", function (err) {
          if (err) return console.log(err)
        })
      })
    })
  }
}

let cssConfig = {
  test: /\.css$/i,
  use: ["css-loader?url=false", { loader: "postcss-loader", options: { postcssOptions :{ plugins: postCSSPlugins } }}]
}

let config = {
  entry: {
    scripts: "./js/scripts.js"
  },
  plugins: [],
  module: {
    rules: [
      cssConfig,
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-react", ["@babel/preset-env", { targets: { node: "12" } }]]
          }
        }
      }
    ]
  }
}

if (currentTask == "devFast") {
  config.devtool = "source-map"
  cssConfig.use.unshift("style-loader")
  config.output = {
    filename: "bundled.js",
    publicPath: "http://localhost:3000/"
  }
  config.devServer = {
    before: function (app, server) {
      // server._watch(["./**/*.php", "./**/*.js"])
      server._watch(["./**/*.php", "!./functions.php"])
    },
    public: "http://localhost:3000",
    publicPath: "http://localhost:3000/",
    disableHostCheck: true,
    contentBase: path.join(__dirname),
    contentBasePublicPath: "http://localhost:3000/",
    hot: true,
    port: 3000,
    headers: {
      "Access-Control-Allow-Origin": "*"
    }
  }
  config.mode = "development"
}

if (currentTask == "build" || currentTask == "buildWatch") {
  cssConfig.use.unshift(MiniCssExtractPlugin.loader)
  postCSSPlugins.push(require("cssnano"))
  config.output = {
    publicPath: "/wp-content/themes/workshop_01/bundled-assets/",
    filename: "[name].[chunkhash].js",
    chunkFilename: "[name].[chunkhash].js",
    path: path.resolve(__dirname, "bundled-assets")
  }
  config.mode = "production"
  config.optimization = {
    splitChunks: { chunks: "all" }
  }
  config.plugins.push(new CleanWebpackPlugin(), new MiniCssExtractPlugin({ filename: "styles.[chunkhash].css" }), new WebpackManifestPlugin({ publicPath: "" }), new RunAfterCompile())
}

module.exports = config

enter image description here

有人能明白为什么它不自动刷新吗?

两周后,我仍在努力解决这个问题,所以如果有人能提供帮助,我将不胜感激。

0 个答案:

没有答案