【问题标题】:How to import HTML files as templates into Rollup and compile to concatenated strings如何将 HTML 文件作为模板导入 Rollup 并编译为串联字符串
【发布时间】:2019-05-20 16:27:55
【问题描述】:

我正在使用 Rollup 为 Optimizely 实验创建构建过程。我们目前使用的是 Webpack,但它为这个用例导出了臃肿的代码。我希望能够将 .html 文件作为模板导入,并在我的 Rollup/Babel 构建中将它们编译为 ES5 兼容的串联字符串。

我已经在https://github.com/rollup/awesome#templating 尝试了一些模板插件,但不想添加另一个模块库作为每个实验的依赖项。我能够使用几个插件将 HTML 作为模板文字导入,但由于某种原因,它们无法通过 babel 编译为 ES5 兼容的字符串。 Babel 似乎只将内联(未导入)模板文字编译为连接字符串。其他一切都正确编译为 ES5。不确定为什么不包含外部 HTML 字符串。也许我的问题是 babel 配置?

我们在 Webpack 构建中使用的方法使用了 html-es6-template-loader,它内置了编译功能,因此它可以生成开箱即用的 ES5 兼容字符串连接。类似的东西可能是理想的。

这是我目前的配置。在这里使用 posthtml,但我尝试了多个插件,结果相同。

import babel from 'rollup-plugin-babel';
import posthtml from 'rollup-plugin-posthtml-template';

export default {
    input: './src/index',
    output: {
        file: './dist/index.js',
        format: 'cjs'
    },
    plugins: [
        posthtml({
            template: true
        }),
        babel({
            exclude: 'node_modules/**',
            presets: ['@babel/preset-env']
        })
    ]
}

理想的场景是从 HTML 文件作为 es6 ${} 语法的模板开始,导入到 JS 文件中,然后编译成带有内联串联字符串的 JS 文件。

模板.html

<div class="some-div">hello ${data.entity}</div>

用现代 ES 版本编写的 index.js

import template from './template.html';
console.log(template({entity="world"})); // logs: <div class="some-div">hello world</div>

我希望结果是编译后的与 ES5 兼容的脚本,而不需要额外的模板代码。结果将类似于下面的代码。

var template = function(data){
  return '<div class="some-div">hello ' + data.entity + '</div>';
}
console.log(template({entity="world"})); // logs: <div class="some-div">hello world</div>

【问题讨论】:

  • 我认为您需要评估模板
  • @DerekPollard 如果你的意思是把它包装在 eval() 我宁愿找到一种不同的方式
  • 嗯,这样就可以了,不用手动解析 HTML
  • @DerekPollard 你能详细说明你将如何使用 eval 吗?

标签: javascript rollup template-literals


【解决方案1】:

如果您只想将.html 文件作为字符串导入,那么您也可以尝试使用rollup-plugin-html

// rollup.config.js
import html from "rollup-plugin-html";

export default {
  input: "./index.js",
  plugins: [
    html({
      include: "**/*.html",
    }),
  ],
  output: {
    file: "my-module.js",
    name: "MyModule",
    format: "umd",
  },
};

【讨论】:

  • 是的,这是完美的。 rollup-plugin-html ... 效果很好。
  • 不要与@rollup/plugin-html混淆
【解决方案2】:

我想出了解决办法。我只需要将 HTML 添加到 babel 配置中。之前我认为不需要这样做,因为我认为 babel 只是在 HTML 导入并转换为模板文字后解析 JS 文件,但我想它是需要的。

我在查看docs on external dependencies for rollup-plugin-babel 时发现了这一点

babel({
    exclude: 'node_modules/**',
    presets: ['@babel/preset-env'],
    extensions: ['.js', '.html']
})

【讨论】:

    猜你喜欢
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 2018-08-30
    相关资源
    最近更新 更多