loader让 webpack能够去处理那些非js文件(webpack自身只理解js),去转化成浏览器能解析的语言。
编写一个自定义loader的dome,用内容去填充模板里面的{{}}里的内容
需要使用 安装 插件
webpack,webapck-cli,webpack-dev-server,babel-loader,@babel-core
下面是我的目录结构
1.先构建一个新的项目
npm init -y
安装以上需要的插件
package.js里面 添加命令
"scripts": {
"dev": "webpack server"
},
因为我安装的webpack是5.x的 ,webpack-dev-server在5版本下换 webpack server 就可以了
2.编写webpack.config.js
先写一个最简单的基本配置
const { resolve } = require("path");
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports ={
mode: "development",
entry:resolve(__dirname,"src/app.js"),
output:{
path:resolve(__dirname,'dist'),
filename:'app.[contenthash:8].js',
},
devtool:'source-map',
devServer:{
open:true,
port:8080,
host: 'localhost'
},
plugins:[
new htmlWebpackPlugin({
template:resolve(__dirname,'index.html'),//入口文件
//打包之后的文件名
filename:'index.html',
minify:{
removeAttributeQuotes:true,//打包的时候双引号没了
collapseWhitespace:true//单行压缩
}
})
],
}
3.编写自定义loader
当前路径下,创建一个文件夹loaders,在创建要使用的tpl-loader文件夹和它的index.js
//webpack.config.js
module.exports ={
...,
resolveLoader:{
modules:['node_modules',resolve(__dirname,'loaders')]
},
module:{
rules:[
{
test: /\.tpl$/,
use:[
'babel-loader',
{
loader:'tpl-loader',
options:{
log:true
}
}
]
}
]
},
}
一定要resolveLoader,这是我们loader需要依赖的来源
4.写入info.tpl模板和tpl-loader的index.js
info.tpl
<div>
<h3>{{title}}</h3>
<p>{{info}}</p>
</div>
tpl-loader/index.js
//loader 就是一个函数,接受的参数就是source,返回一个source
const { tplReplace } = require("./utils");
//webapck 专门为loader提供的方法
const loaderUtils = require("loader-utils")
function tplLoader(source) {
//去除空格
source = source.replace(/\s+/g,'');
//options处理
const {log} = loaderUtils.getOptions(this);
const _log = log?`console.log('compiled the file which is from ${this.resourcePath}')`:''
//这里面是一个运行的字符串
return `
export default (options) => {
${ tplReplace.toString() }
${ _log.toString() }
return tplReplace( '${source}' ,options);
}`
}
//commonjs规范
module.exports = tplLoader;
5.tpl-loader的utils.js -->模板的转化
function tplReplace(template,replaceObject){
//替换模板中的{{}}里面的内容
return template.replace(/\{\{(.*?)\}\}/g,(node,key)=>{
return replaceObject[key];
})
}
module.exports = {
tplReplace
}
6.在app.js 引入模板使用
import tpl from "./info.tpl";
const oApp = document.querySelector('#app');
oApp.innerHTML = tpl({
title:'自定义loader',
info:'tpl-loader',
})
7.npm run dev 跑起服务就可以看到效果啦