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

问题描述 投票:0回答:1

我想使用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>';
javascript babel
1个回答
0
投票

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

步骤1

将Babel导入文档。

步骤2

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

 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 Fiddle中添加了对此的支持。在此处查看示例:https://fiddle.sencha.com/#view/editor&fiddle/30vv。如果您检查devtools,它将位于require.js中。

© www.soinside.com 2019 - 2024. All rights reserved.