Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why can’t I automatically refresh the html after I modify it #3881

Closed
ipsum-0320 opened this issue Sep 25, 2021 · 7 comments
Closed

Why can’t I automatically refresh the html after I modify it #3881

ipsum-0320 opened this issue Sep 25, 2021 · 7 comments

Comments

@ipsum-0320
Copy link

ipsum-0320 commented Sep 25, 2021

well, here is my problem, thank you for your help.

Version

webpack ^5.53.0
webpack-cli ^4.8.0
webpack-dev-server ^4.2.1
webpack-merge ^5.8.0
html-webpack-plugin ^5.3.2

Folder structure

image

webpack configuration

  1. webpack.common.js
/* 自己封装的工具 */
const prodConfig = require('./webpack.prod');
const devConfig = require('./webpack.dev');
const resolveApp = require('./path');

/* 第三方库 */
const { merge } = require('webpack-merge');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { DefinePlugin } = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

function getHtmlPlugin(option) {
  return new HtmlWebpackPlugin({
    template: `./src/${option.path}`,
    filename: `./html/${option.chunk}.html`,
    chunks: option.chunk,
    // 输出的 html 文件引入资源文件的入口 chunk。
    // 这个 chunk 和多入口的配置相关。
    inject: true,
    hash: true
  });
}

function commonConfig(isProduction) {
  return {
    context: resolveApp('./'),
    entry: {
      // 配置多入口。
      navbar: './src/component/navbar/script/index.js',
    },
    output: {
      filename: 'js/[name].[hash:6].bundle.js',
      path: resolveApp('./dist'),
    },
    plugins: [
      getHtmlPlugin({
        path: 'component/navbar/index.html',
        chunk: 'navbar'
      }),
      new DefinePlugin({
        BASE_URL: "'../'",
      }),
      // 用来定义全局变量的插件,暂且还不需要,
      new CopyWebpackPlugin({
        patterns: [
          { from: './src/public' }
        ]
      })
    ],
    module: {
      rules: [
        {
          test: /\.js$/i,
          exclude: /node_modules/,
          // 排除对 node_modules 文件夹中 js 文件的 babel-loader 转化。
          use: 'babel-loader',
        },
        {
          test: /\.scss$/i,
          use: [
            isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
            {
              loader: 'css-loader',
              options: {
                importLoaders: 2
              }
            },
            'postcss-loader',
            'sass-loader'
          ]
        },
        {
          test: /\.(jpe?g|png|gif|svg|)$/i,
          use: [
            {
              loader: 'url-loader',
              options: {
                name: '[name].[hash:6].[ext]',
                outputPath: 'img',
                limit: 10 * 1024,
              }
            },
          ]
        }
      ]
    },
    resolve: {
      extensions: ['.js', '.scss', '.html', '.mjs', '.css'],
      alias: {
        "@": resolveApp('./src')
      }
    }
  }
}

module.exports = function (env) {
  process.env.NODE_ENV = env.production ? 'production' : 'development';
  const config = env.production ? prodConfig : devConfig;
  return merge(commonConfig(env.production), config);
}
  1. webpack.dev.js
module.exports = {
  mode: "development",
  devtool: 'cheap-module-source-map',
  devServer: {
    /* 需要注意一下,现在使用的 webpack-dev-server 版本已经是 v4 了,
    很多配置都改变了,需要我们重新阅读一下官方文档。 */
    open: ['/html/navbar.html'],
    // 打开默认的文件,即这里访问的网址是 http://127.0.0.1:8899/html/navbar.html。
    host: 'localhost',
    port: 8899,
    hot: "only",
    // 启用热模块替换功能,在构建失败时不刷新页面作为回退。
    proxy: {
      "/api": {
        target: "http://120.77.83.8:8084",
        pathRewrite: {
          "^/api": ""
        },
        secure: false,
        changeOrigin: true
      }
    },
    historyApiFallback: {
      // 用来解决 SPA 页面在路由跳转之后,进行页面刷新时,返回 404 的问题。
      rewrites: [
        { from: /\*/, to: "./index.html" }
      ]
    },
  },
}

My problem description

I remember that html file will be refreshed automaticlly by webpack-dev-server when I change the content.
but now it doesn't work.

here is related js file and html file

  1. js file
if (process.env.NODE_ENV === 'development') {
  /* 这是用来实现 HMR 的代码,JS 模块中只有存在了这段代码才会开启 HMR。 */
  module.hot.accept((err) => {
    console.error(err);
  });
}

import '../style/main';

console.log(4);

console.log(7);

console.log(9);

console.log(10);

console.log(1);
  1. html file
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>铁思汇</title>
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
  </head>
  <body>
    <div id="nav-bar">
      <!--some html code-->
    </div>
  </body>
</html>
@alexander-akait
Copy link
Member

If you want to help please use the issue template, screenshots is not enough to help, sorry, no versions/no examples usage, no configuration, format your issue using the bug template and I will reopen and help you

@ipsum-0320
Copy link
Author

If you want to help please use the issue template, screenshots is not enough to help, sorry, no versions/no examples usage, no configuration, format your issue using the bug template and I will reopen and help you

sorry, this is my first time to create a issue, I will format it now.

@alexander-akait
Copy link
Member

Feel free to ping me when it will be ready

@ipsum-0320
Copy link
Author

@alexander-akait Thanks so much for your help. (maybe my format is still terrible.

@alexander-akait
Copy link
Member

@KK-wang Can you create github repo? it will be easier to say what is wrong. And what is meaning automatically refresh? Reload page? Note - it is HTML page, HMR is impossible

@ipsum-0320
Copy link
Author

@alexander-akait I am sorry to reply you now... well here is my repo:

https://github.com/KK-wang/tie-project-front

And "automatically refresh" means reload page when I modify the html code.
(My mother tongue is not English, forgive my poor grammar and expression...)

@alexander-akait
Copy link
Member

Because you need to be told what to do with changes for component/navbar/index.html, you can use watchFiles: ['src/component/**/*.html'], duplicate #3794

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants