如何从 webpack 编译的模板文字中删除 \n 和 \t?

How to remove \n and \t from webpack compiled template literal?

我正在开发一个javascript插件,它使用es6模板文字生成模板,我在我的插件中附上了一段代码。

"use strict";
(function () {
window.project = {
    template: {
        generateHtmlTemplate: function(data) {
        var template = `
             <div class="main">
                <div class="wrap">
                    <input type="text" value="${data.val}" />
                </div>
             </div>`;
       return template;
      }
   }
}

当我尝试通过 webpack 构建时,babel 将其转换为 es5,因此模板文字如下所示。这是插件的 webpack 缩小 babel 转译版本。这个缩小的转译文件供用户使用。此生产版本缩小文件包含 \n \t,这是我要删除的内容。

(想想jQuery开发版用es6写的,用babel和webpack转译压缩成jquery.min.js)

"use strict";
(function () {
window.project = {
    template: {
        generateHtmlTemplate: function(data) {
        var template = '<div class="main">\n\t\t\t<div class="wrap">\n\t\t\t\t<input type="text" value="${data.val}" />\n\t\t\t\t\t</div>\n\t\t\t\t\t</div>';
       return template;
      }
   }
}

用\n和\t填充。我已经尝试了一些 。但这对我不起作用。这个 common-tags 包的作用是 注入删除 \n 和 \t 的代码以及插件代码 .

我想要的

只需从输出文件中删除 \n 和 \t。

我试过的

  1. 我试过 webpack string replace 插件来替换 \t 和 \n。但它不起作用。它获取源代码并尝试在转译器工作之前进行替换。
  2. 我通过在每行末尾添加 \ 来解决换行问题(代码也变得混乱)。但即使 \t 在那里。
  3. 如果我在构建和替换后尝试对所有 \n 和 \t 进行正则表达式,这不是一个好方法,它很容易出错。

Webpack 生产构建配置

const TerserPlugin = require('terser-webpack-plugin');
const ReplacePlugin = require('webpack-plugin-replace');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const MiniCssExtactPlugin = require('mini-css-extract-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const BrotliPlugin = require('brotli-webpack-plugin');

const config = {
    mode: 'production',
    entry: ['./src/source.js', './src/ufe.css'],
    output: {
        path: __dirname + '/dist/',
        filename: 'source.min.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            },
            {
                test: /\.css$/,
                use: [MiniCssExtactPlugin.loader, 'css-loader']
            },
            {
                test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
                use: 'url-loader?limit=100000'
            }
        ]
    },

    plugins: [
        // new uglifyJsPlugin(),
        // new ReplacePlugin({
        //     values: {
        //         "\n": '',
        //         "\t": ''
        //     }
        // })
        }),
        // Brotli compression output for files
        new CompressionPlugin({
            filename: '[path].gz[query]',
            algorithm: 'gzip',
            test: /\.js$|\.css$|\.html$|\.svg$/,
            threshold: 1024,
            minRatio: 0.8
        }),
        new BrotliPlugin({
            asset: '[path].br[query]',
            test: /\.js$|\.css$|\.html$|\.svg$/,
            threshold: 1024,
            minRatio: 0.8
        })
        // new HTMLWebpackPlugin({
        //  template: path.resolve(__dirname, 'index.html')
        // }),
        // new webpack.HotModuleReplacementPlugin()
    ],
    optimization: {
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    ecma: undefined,
                    warnings: false,
                    parse: {},
                    compress: {},
                    mangle: true, // Note `mangle.properties` is `false` by default.
                    module: false,
                    output: null,
                    toplevel: false,
                    nameCache: null,
                    ie8: false,
                    keep_classnames: undefined,
                    keep_fnames: false,
                    safari10: false,
                }
            }),
            new OptimizeCssAssetsPlugin({})
        ],
    },
    resolve: {
        extensions: ['.js', '.svg']
    },
    devServer: {
        port: 3000,
        contentBase: __dirname + '/build',
        inline: false
    }
};
module.exports = config;

任何解决此问题的建议将不胜感激。

提前致谢。

这不是模板文字的工作方式:它们保留空白。此功能是有意为之的,因为它允许您像其他语言中的格式化字符串一样保留格式(例如 PHP and triple-quoted strings in python 中的 heredocs)。如果你不想要这种行为,那么你可以像我们在 ES 6 之前的旧时代所做的那样连接纯字符串:

window.project = {
    template: {
        generateHtmlTemplate: function(data) {
        var template = '' +
             '<div class="main">' +
                '<div class="wrap">' +
                    '<input type="text" value="' + data.val + '" />' +
                '</div>' +
             '</div>';
        return template;
      }
   }
}

请注意,这在源代码中更难阅读。在有效负载中保存少量字节是否值得是主观的,但 FWIW 我会坚持使用模板字符串。

编辑

如果您真的想使用模板但去掉空格,只需这样做:

function(data) {
    var template = `
        <div class="main">
            <div class="wrap">
                <input type="text" value="${data.val}" />
            </div>
        </div>`.replace(/[\t\n]+/g, ''); // remove all tabs and returns
    return template;
}

我已经找到了我想要的解决方案。

创建一个 babel 插件来删除它。

var pattern = new RegExp("[\n\t ]+", "g");

function transfrom (quasis) {
  ["raw", "cooked"].forEach(function (type) {
    quasis.forEach(function (element) {
      element.value[type] = element.value[type].replace(pattern, " ");
    });
  });  
}

module.exports = function (babel) {
  var t = babel.types;

  return {
    visitor: {
      TaggedTemplateExpression: function (path) {
        let node = path.node;

        if (t.isIdentifier(node.tag, { name: "nowhitespace" })) {
          transfrom(node.quasi.quasis);
          return path.replaceWith(node.quasi);
        }
      }
    }
  };
};

它有点旧,但仍然有效。

https://github.com/WebEngage/babel-plugin-template-string-transform https://engineering.webengage.com/2016/07/15/babel/