如何使用Babel独立版将html导入转换为变量?

我想使用Babel插件babel-plugin-transform-html-import-to-string在浏览器客户端中动态转换我的代码。但是babel-plugin-transform-html-import-to-string是为从具有文件库的节点运行而构建的。但是在浏览器中,我无法使用这些文件库。

Babel Standalone如何转换此代码?

我的声明:

import template from './template.html';

转换为:

var template = '<div>my template<div>';
ganmazhememahuan 回答:如何使用Babel独立版将html导入转换为变量?

我找到了一种简单的方法来包含babel-plugin-transform-html-import-to-string转换库中内置的插件代码。

第1步

将Babel导入文档。

第2步

然后,我获取了代码,并删除了文件库,并为代码html添加了字符串值。此代码来自library

 function endsWith(str,search) {
    return str.indexOf(search,str.length - search.length) !== -1;
  }

  // transform `import template from 'file.html';` to a variable `var template = '<div></div>'`;
  function babelPluginImportHtmlToString(o) {
    var t = o.types;
    return {
      visitor: {
        ImportDeclaration: {
          exit: function (path,state) {
            const node = path.node;

            if (endsWith(node.source.value,'.html')) {
              const html = require(node.source.value);

              path.replaceWith(t.variableDeclaration("var",[
                t.variableDeclarator(
                  t.identifier(node.specifiers[0].local.name),t.stringLiteral(html))]));
            }
          }
        }
      }
    };
  }

第3步

然后我将该功能注册为Babel插件。然后称为使用插件的转换过程。

  var plugins = [];
  plugins.push('babelPluginImportHtmlToString');

  babel.registerPlugin('babelPluginImportHtmlToString',babelPluginImportHtmlToString);

  // TODO I'm not showing the babel import statement,include a reference to babel...
  var code = babel.transform(code,{
    filename: filename,plugins: plugins,presets: presets
  }).code;

示例

我在这里的Sencha小提琴中添加了对此的支持。在此处查看示例:https://fiddle.sencha.com/#view/editor&fiddle/30vv。如果您检查devtools,它将位于require.js中。

本文链接:https://www.f2er.com/3136033.html

大家都在问