在JavaScript中根据需要解析HTML模板 [英] Parse an HTML template as you require it in JavaScript

查看:149
本文介绍了在JavaScript中根据需要解析HTML模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了几个小时进行基本的Webpack配置,但仍无法使它正常工作.我的目标是在将HTML模板导入JavaScript文件时执行html模板的解析.看起来像是一个普通的用例,但是在我的webpack配置或我的理解中应该有些奇怪.

I spent hours on a basic webpack configuration but I'm still not able to make it work. My aim is to perform the parsing of a html template as you import it in a JavaScript file. It looks like a common use-case, but there should be something odd in my webpack configuration or in my understanding.

我在寻找html-loaderhtml-webpack-pluginposthtml以及pug的配置,并且我已经阅读了所有文档,但没有一个起作用.

I looked for configurations of html-loader, html-webpack-plugin, posthtml as well as pug and I've read all of their documentations, but none of them worked.

根据 PostHTML自述文件:

PostHTML是用于使用JS插件转换HTML/XML的工具. PostHTML本身很小.它仅包含HTML解析器,HTML节点树API和节点树字符串.

PostHTML is a tool for transforming HTML/XML with JS plugins. PostHTML itself is very small. It includes only a HTML parser, a HTML node tree API and a node tree stringifier.

因此,由于这是最有前途的,所以我用posthtml报告了我的尝试:

So, since it was the most promising, I report my attempt with posthtml:

   rules: [
      {
        test: /.html$/,
        use: [
          {
            loader: "html-loader",
            options: {
              minimize: true,
              interpolation: false
            }
          },
          {
            loader: "posthtml-loader"
          }
        ]
      }
    ]

它不返回任何错误,但看起来完全忽略了posthtml-loader,因为执行import template from 'src/test.html'后,我将模板作为字符串获取(应该单独执行html-loader).

It doesn't return any error but it looks like is totally ignoring the posthtml-loader, since executing import template from 'src/test.html' I get the template as string (how is supposed to do html-loader alone).

据我了解,加载程序应该以不同的格式编译/转换文件并使它们可用于JavaScript,并且由于html是前端项目中最常见的类型,所以我认为这很容易,但是我我没有在互联网上找到与此问题有关的任何东西.

In my understanding, loaders are supposed to compile/transform files with different formats and make them available to JavaScript, and since html is the most common type in a front-end project I supposed it was easy, but I'm not finding anything on the internet related to this question.

我希望有一个DOM树对象,或者无论如何都可以由JavaScript使用.

What I expect is to have a DOM tree object or, anyway, something that can be used by JavaScript.

有人可以帮助我吗?

编辑:我的问题是有关配置Webpack并使其正常工作的问题.我知道许多用于解析HTML字符串的解决方案,但它们不适用于此处

My question is about getting a webpack configuration up and working. I know many solution for parsing HTML strings, but they're not applicable here

推荐答案

在我看来,posthtml-loader主要是一个工具,可帮助您在构建过程中准备" HTML.它的解析器选项使您可以进入string -> PostHTML AST Tree步骤,其插件选项使您可以修改树.然后,将其字符串化回HTML.

To me it seems like the posthtml-loader is primarily a tool that helps to "prepare" your HTML during the build. Its parser options allow you to break in to the string -> PostHTML AST Tree step, and its plugin options allow you to modify the tree. Then, it stringifies back to HTML.

我在webpack插件中找不到返回临时树格式的选项.

I couldn't find an option in the webpack plugin to return the interim tree format.

您可以编写一个小的自定义加载程序,以将HTML字符串解析为DOM对象:

You could write a small custom loader to parse HTML strings to DOM objects:

// custom-loader.js
module.exports = function(content) {
  return `module.exports = (function() {
    const parser = new DOMParser();
    const doc = parser.parseFromString("${content}", "text/html");
    return doc.body.children; 
  }())`;
};

然后,在您的webpack.config.js中,您可以告诉webpack使.html文件通过此加载器:

Then, in your webpack.config.js, you can tell webpack to make .html files pass this loader:

// webpack.config.js
module.exports = {
  mode: 'development',
  entry: './main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.bundle.js'
  },
  devtool: "eval-source-map",
  module: {
    rules: [
      {
        test: /\.html$/,
        use: [ './custom-loader' ]
      }
    ]
  }
};

现在,每当您键入类似const template = require('./template.html');的内容时,您都会得到一个

Now, whenever you type something like const template = require('./template.html'); you'll get an HTMLCollection instance rather than just a string.

请注意,此加载器向DOMParser添加了一个依赖项,该依赖项仅在浏览器中可用.如果要在非浏览器环境中运行,可以用jsdom代替.

Note that this loader adds a dependency to DOMParser, which is only available in the browser. You could replace it by something like jsdom if you want to run in non-browser environments.

这篇关于在JavaScript中根据需要解析HTML模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆