velocity-render-loader

java-velocity/vm loader for webpack

Usage no npm install needed!

<script type="module">
  import velocityRenderLoader from 'https://cdn.skypack.dev/velocity-render-loader';
</script>

README

Velocity Render Loader

webpack中使用Velocity.js解析vm模板,支持#parse指令。

Install

npm install --save-dev velocity-render-loader html-loader

Usage

首先在webpack配置中匹配规则

module: {
  rules: [
    {
      test: /\.vm$/,
      use:[
        {
          loader: 'html-loader'
        },
        {
          loader: 'velocity-render-loader'
        }
      ]
    }
  ]
}

自动生成html文件

new HtmlWebpackPlugin({
  filename: 'a.html',
  template: '/path/to/a.vm', 
  inject: true
}

velocity-render-loader会自动读取vm文件旁的同名mock文件,假设结构如下

=====================
- src
  - modules
    - a
      - a.vm
      - a.mock.js
  - shared
    - components
      - header
        - header.vtl
======================

在mock中定义变量并通过模块暴露出来

//a.mock.js
module.exports = {
  title : "Hello World!"
}

在vm中使用变量

<!--a.vm-->

<!--编译前-->
<head>
  <title>$title</title>
</head>

<!--编译后-->
<head>
  <title>Hello World!</title>
</head>

更多支持的指令见 https://github.com/shepherdwind/velocity.js

Options

options: {
  basePath: path.join(__dirname, 'src')
}

配置项:

  • basePath: 定义#parse指令中绝对路径的起始位置

      #parse("/shared/components/header/header.vtl")
    

    在某些情况下,后端渲染vm时的相对路径与前端环境不同。最好使用绝对路径来查找文件位置。

  • compileVm: 是否开启vm解析器,默认为true

  • compileEjs: 是否开启ejs解析器,默认为false

  • removeComments 是否去除vm注释,默认为false

    删除vm注释后,可以使用html-minifier等工具进行压缩