webpack自定义loader--编译.tpl文件

一、初始化一个项目

1、npm 初始化

npm init -y

2、安装需要的依赖

package.json文件:

{
  "name": "webpack-plugin-test",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.18.6",
    "babel-loader": "^8.2.5",
    "html-webpack-plugin": "^5.5.0",
    "webpack": "^5.73.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.9.3"
  }
}

3、新建文件tpl-loader,info.tpl,主入口文件main.js,webpack配置文件 webpack.config.js
在这里插入图片描述

二、编写info.tpl和主入口文件main.js文件,配置webpack

//  info.tpl文件:

<div>
  <h1>{{ name }}</h1>
  <div>{{ age }}</div>
  <div>{{ sex }}</div>
</div>

//  main.js文件:

import tpl from './info.tpl';

const appDom = document.getElementById('app');

appDom.innerHTML = tpl({
  name: '张三',
  age: 19,
  sex: '男'
})


//  webpack.config.js文件:

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

module.exports = {
  mode:'development',
  devtool: 'eval-cheap-module-source-map',
  // 一般开发环境配置
	// development devtool: 'eval-cheap-module-source-map',
	// 一般情况生产环境配置
	// production devtool: 'cheap-module-source-map',
  entry:'./src/main.js',
  output:{
    filename: 'bundle.js',
    path:resolve(__dirname,'./dist')
  },
  
  resolveLoader: {
    modules: [ 'node_modules',resolve(__dirname,'loaders')]
  },
  module: {
    rules: [
      {
        test: /\.tpl$/,
        use: [
          'babel-loader',
          {
            loader: 'tpl-loader',
            options: {
              log: true
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template:'./public/index.html',
      filename: 'index.html',
      minify:false
    })
  ],
  devServer: {
    port: 9000
  }
}

三、自定义tpl-loader

// tpl-loader/index.js 文件:
function tpl(source){
  console.log(source);
  // 去掉所有空格
  source = source.replace(/\s+/g, '');
  return `
    export default (options) => {
      ${compilerDom.toString()}
      return compilerDom('${source}',options);
    }
  `
}

// 替换{{}}内部内容

function compilerDom(source,replaceObj){
  const result = source.replace(/\{\{(.*?)\}\}/g,function(node,key){
    return replaceObj[key]
  })
  return result
}


module.exports = tpl;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值