Christian-Yang / Translate-and-save

Translate and save for my self
1 stars 0 forks source link

string-replace-webpack-plugin #26

Open Christian-Yang opened 7 years ago

Christian-Yang commented 7 years ago
var StringReplacePlugin = require("string-replace-webpack-plugin");
module.exports = {
   module: {
      loaders: [
         // configure replacements for file patterns 
         { 
            test: /index.html$/,
            loader: StringReplacePlugin.replace({
                replacements: [
                    {
                        pattern: /<!-- @secret (\w*?) -->/ig,
                        replacement: function (match, p1, offset, string) {
                            return secrets.web[p1];
                        }
                    }
                ]})
            }
      ]
   },
   plugins: [
      // an instance of the plugin must be present 
      new StringReplacePlugin()
   ]
}

This allows for arbitrary strings to be replaced as part of the module build process. The original intent is to replace API keys in modules prior to deployment.

这允许任意字符串被替换为模块构建过程的一部分。 原来的意图是在部署之前替换模块中的API密钥。

API:

StringReplacePlugin.replace([nextLoaders: string], options, [prevLoaders: string])

你不是担心,如果一个字符串,没有被替换掉,这个时候就已经开始被ts loader替换掉了吗? 没事有这个nextLoades和prevLoaders

•   nextLoaders loaders to follow the replacement  对字符串进行替换之后,处理文件的loader
•   options
•   replacements disables the plugin    禁用这个插件
•   pattern a regex to match against the file contents正则表达式匹配文件内容  
•   replacement an ECMAScript string replacement function 一个函数
•   prevLoaders loaders to apply prior to the replacement 对字符串进行替换之前使用的loader

1 2 3

Christian-Yang commented 7 years ago

例如,要在项目中取代这个字符串<%= BASE_URL =>可以使用下面这个代码,运行成功了

 { 
            test: /\.ts$/,
            loader: StringReplacePlugin.replace({
                replacements: [
                    {
                        pattern: /<%= BASE_URL =>/ig,
                        replacement: function (match, p1, offset, string) {
                            var mypath = ""+path.resolve(__dirname,'../dist');
                            console.log('path==========',mypath);
                            return 'woshiyangxuefenga';
                        }
                    }
                ]})
            }