如何从webpack编译模板文字中删除\ n和\ t? [英] How to remove \n and \t from webpack compiled template literal?

查看:87
本文介绍了如何从webpack编译模板文字中删除\ n和\ t?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个JavaScript插件,该插件使用es6模板文字来生成模板,我在插件中附加了一段代码.

I am developing a javascript plugin, which uses es6 template literals to generate a template, I am attaching a piece of code in my plugin.

"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进行构建时,babel将其转换为es5,因此模板文字如下所示.这是该插件的 webpack缩小的babel编译版本.用户使用了此最小化的已编译文件.此生产版本的缩小文件包含\ n \ t,这是我要删除的文件.

When i tried to get build via webpack babel transpiles it to es5 so the template literals like the following. This is the webpack minified babel transpiled version of the plugin. This minified transpiled file is used by users. This production build minified file contains \n \t, this is what i want to remove.

(就像以es6编写并使用babel和webpack进行编译和缩小以形成jquery.min.js的jQuery开发版本一样)

(Just think like jQuery development version written with es6 and using babel and webpack to transpile and minify it to form 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填充.我已经尝试过一些 stackoverflow解决方案.但这对我不起作用.此common-tags软件包的作用是注入代码以删除\ n和\ t以及插件代码.

It is filled with \n and \t. I have tried some the solutions in stackoverflow. But it doesn't work for me. What this common-tags package does is it injects the code to remove \n and \t along with the plugin code.

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

Just remove \n and \t from the output file.

  1. 我尝试了 webpack字符串替换插件来替换\ t和\.但这是行不通的.它需要源代码,并试图在transpiler工作之前进行替换.
  2. 我通过在每行的末尾添加\来解决新行的问题(代码也变得混乱).但是,即使\ t在那里.
  3. 如果我在构建和替换后尝试对所有\ n和\ t进行正则表达式不是一个好方法,则容易出错.
  1. I have tried webpack string replace plugin to replace \t and \n. But it doesn't worked. It take source code and tried to replace before transpiler works.
  2. I got a hack to solve new line problem by adding \ to the end of each line (also code becomes messy). But even though \t is there.
  3. If i try to regEx all \n and \t after build and replacing it is not a good method, it is error prone.

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;

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

Any suggestions to solve this will be much appreciated.

谢谢.

推荐答案

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

I have got solution for what I want exactly.

创建一个babel插件将其删除.

Create a babel plugin to remove it.

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);
        }
      }
    }
  };
};

它有点旧,但仍然可以使用.

It's bit old, but still works.

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

这篇关于如何从webpack编译模板文字中删除\ n和\ t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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