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

Cap*_*ero 4 javascript webpack babeljs template-literals

我正在开发一个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;
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

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

(就像用 es6 编写的 jQuery 开发版本一样,使用 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;
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

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

我想要的是

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

我尝试过的

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

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;
Run Code Online (Sandbox Code Playgroud)

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

提前致谢。

Cap*_*ero 6

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

创建一个 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);
        }
      }
    }
  };
};
Run Code Online (Sandbox Code Playgroud)

它有点旧,但仍然有效。

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