1. 项目根目录下载 html-loader
npm i html-loader -D
2. 要操作的相关文件:
![](https://img.haomeiwen.com/i5006978/92fde639e7a558df.png)
3. 将相关JS接口暴露出来
demo max.js
module.exports = function(...arg) {
return Math.max(...arg); // Math.max.apply(null, arg)
}
demo min.js
module.exports = function(...arg) {
return Math.min(...arg); // Math.min.apply(null, arg)
}
demo ./tpl/footer.html
<footer>
<p>尾部</p>
</footer>
demo ./tpl/header.html
<header>
<h1>头部</h1>
</header>
demo ./src/index.html文件保持基本框架,内容为空。
demo main.js
// 导入js模块
let min = require('./js/min.js');
let max = require('./js/max.js');
console.log(min(1, 20, 4, 5));
console.log(max(1, 20, 4, 5));
// 导入html片段
let headerHTML = require('./tpl/header.html');
let footerHTML = require('./tpl/footer.html');
console.log(headerHTML);
console.log(footerHTML);
// 插入到页面
let tempDiv = document.createElement('div');
tempDiv.innerHTML = headerHTML;
let tempDiv2 = document.createElement('div');
tempDiv2.innerHTML = footerHTML;
document.querySelector('body').appendChild(tempDiv);
document.querySelector('body').appendChild(tempDiv2);
demo webpack.config.js
/*
* @Author: Robyn
* @Date: 2017-11-17 08:49:28
* @Last Modified by: Robyn
* @Last Modified time: 2017-11-17 08:49:28
*/
// 因为webpack里面有些路径配置, 必须是绝对路径, 导入这个模块是为了调用方法计算路径
const path = require('path');
const htmlWebapckPlugin = require('html-webpack-plugin');
// 配置文件要求我们必须导出一个配置对象
module.exports = {
// 入口
entry: path.resolve(__dirname, './src/main.js'),
// 输出
output: {
// 路径
path: path.resolve(__dirname, './dist'),
// 打包后js文件名
filename: 'bundle_[chunkhash:8].js'
},
// 插件配置
plugins: [
new htmlWebapckPlugin({
template: './src/index.html', // 要处理的html
filename: 'index.html', // 处理后的html名称
inject: 'body', // 自动注入js到什么地方
minify:{ // 压缩优化HTML页面
collapseWhitespace:true, // 合并空白字符
removeComments:true, // 移除注释
removeAttributeQuotes:true // 移除属性上的引号
}
})
],
// loader的作用是为了让webpack可以打包其他类型的模块
module: {
// 配置loader, 该配置选项是必须的
rules: [
// 打包html模版
{
test: /\.(html|tpl)$/,
use: [ 'html-loader' ]
}
]
}
};
4. 在根目录执行webpack
webpack
![]()
网友评论