配置html-webpack-plugin在内存中自动生成文件

一般在如下的配置中,会在内存中自动生成index.html首页,不需要自己引入js文件,该插件会自动在index.html文件中引入js文件。运行之后,自动打开根目录下的index.html首页。

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const htmlPlugin = new HtmlWebpackPlugin({
  template: path.join(__dirname,'./src/index.html'), //需要打包的入口文件,其中__dirname代表当前文件的目录,使用path.join拼接首页源文件的路径
  filename: 'index.html', //在内存中生成的首页的名称
})

module.exports = {
  mode:'development',
  Plugins: [
      htmlPlugin //把插件放入Plugins节点中
  ]
}

但是运行时报错如下:

这一段的意思是webpack.config.js错误,原因是这个配置文件的版本和我们当前安装的webpack的版本不匹配。

configuration.module has an unknown property ‘Plugins’.

接下来这段我们只需要看前面一句,意思是webpack.config.js这个配置文件里的module属性有一个未知的配置项Plugins,原因嘛,就是我们当前安装的webpack版本已经去掉了这个配置。

所以可以到webpack的官网查看对应webpack版本的插件配置,还是配置失败。根据官网的配置,虽然运行之后控制台不报错,但是并不会在浏览器中打开src -> index.html。配置和浏览器结果如下:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode:'development',
  output: {
      path: path.resolve(__dirname,'./src/index.html'),
      filename: 'index.html',
  },
  plugins: [new HtmlWebpackPlugin()],
}
 

进行了多次尝试,终于配置成功,得到了想要的结果,配置代码如下:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode:'development',
  plugins: [new HtmlWebpackPlugin({
      template: path.join(__dirname, './src/index.html'),
      fileName: 'index.html',
  })]
}

 结果是成功运行了src -> index.html首页,并在html中自动引入了dist -> main.js文件(打包过后的)。

猜你喜欢

转载自www.cnblogs.com/banyouxia/p/12159418.html