webpack对html模版的处理

1.首先我们要加公共的base.js加载进来;

webpack对html模版的处理

现把公共的css加载进来

webpack对html模版的处理

在浏览中打开;发现成功加载

webpack对html模版的处理

加载进来其实并不是正直的解决问题 ;问题是在于;我们的html是在我们定义的文件夹下;并不是在dist下: 我们发布的时候只会发dist;还有就是如果那么多版本,不可能每个版本都手写

<link rel="stylesheet" href="../../dist/css/[email protected]">

;这样会很麻烦

 

所以解决办法是:

用webpack插件:

html-webpack-plugin下载插件

webpack对html模版的处理

webpack对html模版的处理

在引入插件之前我们需要格式化输入:

 npm i --save-dev html-webpack-plugin

webpack对html模版的处理

我们可以看到报错了;意思为:警告节点不支持的“[email protected]”与[email protected]预期节点@=6.11.5不兼容。

webpack对html模版的处理

有可能装有Node6.11.5以上的版本后又开始报webpack

webpack对html模版的处理

我们安照要求去装2.0的版本

webpack对html模版的处理

发现成功

webpack对html模版的处理

再输入 插件:

webpack对html模版的处理

我们可以在webpack.json中看到成功的插件

webpack对html模版的处理

之后回到webpack.config.js引入插件:

 

webpack对html模版的处理

再在

 

 plugins: [

    new HtmlWebpackPlugin()

  ]

:

webpack对html模版的处理

再打包

打包前把除了引用的js脚本留下;其它的都删除,因为在dist下会自动打包生成

webpack对html模版的处理

webpack对html模版的处理

解决完后会发现;html模版处理是对一个个html这意味着;每加一个页面;都得写New一个HtmlWebpackPlugin()这显得很乱;

所以我们可以封装一个方法;

webpack对html模版的处理

再在插件里面调用;

webpack对html模版的处理

打包后可以发现在dist文件下多了两个文件

webpack对html模版的处理

配置的文件也是对应的:

webpack对html模版的处理

webpack对html模版的处理

解决了这个问题你会发现,页面的模版每次都要在页面中输入一遍;或者粘贴一遍

其实这个问题也可以解决:

我们先在view文件中建一个layout文件;再在里面建一个html-header.html在里面写如:

webpack对html模版的处理

然后再在需要的页面引入;引入方式:

 

webpack中html-webpack-plugin方法支持<%%>语法我们可以这么引入,

 html-webpack-plugin  支持ejs模板  在html里想要引入外部文件 要用这种格式获取它才行

 

webpack对html模版的处理

webpack对html模版的处理

打包后会发现报错;

webpack对html模版的处理

这种错是因为我们需要下载一个

npm install html-loader --save-dev这个插件

webpack对html模版的处理

发现安装完后还是报错:

webpack对html模版的处理

我们应该在<%%>中声明文档类型

webpack对html模版的处理

之后再打包会发现;

dist文件生成了;

webpack对html模版的处理

作者:https://blog.****.net/qq_40190624/article/details/79577499