Giter Club home page Giter Club logo

string-replace-loader's People

Contributors

balping avatar deadmann avatar deleonio avatar dependabot[bot] avatar donaldpipowitch avatar hydra1983 avatar kennydude avatar sashless avatar smartin85 avatar va1 avatar valeryvs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

string-replace-loader's Issues

Reference `webpack.DefinePlugin` in the readme

webpack.DefinePlugin offer a native way to run simple replacements, which covers the first example.

I can open a PR that adds a link to this issue as documentation in the readme, and add more examples, including dynamic ones like refined-github/refined-github@130c110

With this loader

module.exports = {
  module: {
    rules: [
      {
        test: /fileInWhichJQueryIsUndefined\.js$/,
        loader: 'string-replace-loader',
        options: {
          search: '$',
          replace: 'window.jQuery',
        }
      }
    ]
  }
}

With DefinePlugin

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      $: 'window.jQuery'
    })
  ]
}

Does not replace text while app running with hot-reload.

Issue: Does not replace text while app running with hot-reload.

Config

{
  loader: 'string-replace-loader',
    options: {
      search: '__SMALL_VIEW_MEDIA_QUERY__',
      replace: `max-width: ${webpackCompileTimeVars.smallViewMaxWidth}px`
    }
}

Compile Time Replacement Works Great

Screenshot 2024-03-22 at 6 44 50 AM

Hot-Update Payload is not Transformed by Plugin

Screenshot 2024-03-22 at 6 47 28 AM

System Info

  System:
    OS: macOS 14.3.1
    CPU: (10) arm64 Apple M1 Pro
    Memory: 1.20 GB / 32.00 GB
  Binaries:
    Node: 18.19.0 - ~/.nvm/versions/node/v18.19.0/bin/node
    Yarn: 1.22.18 - /opt/homebrew/bin/yarn
    npm: 10.2.3 - ~/.nvm/versions/node/v18.19.0/bin/npm
  Browsers:
    Edge: 122.0.2365.92
    Safari: 17.3.1
  Packages:
    babel-loader: 9.1.3 => 9.1.3 
    copy-webpack-plugin: 12.0.2 => 12.0.2 
    css-loader: 6.8.1 => 6.8.1 
    html-webpack-plugin: 5.5.4 => 5.5.4 
    string-replace-loader: 3.1.0 => 3.1.0 
    webpack: 5.90.3 => 5.90.3 
    webpack-cli: 5.1.4 => 5.1.4 
    webpack-hot-middleware: 2.26.1 => 2.26.1 
    webpack-manifest-plugin: 5.0.0 => 5.0.0 
  Global Packages:
    webpack: 5.90.3

How can I enable this transformation for hot-reload?

Unexpected token on 'static' declaration

Hello,

got an error with webpack 4.20.2 and string-replace-loader 2.1.1 on my static declaration.
if i comment this line, everything work file.

ERROR in ./Users.js 14:21
Module parse failed: Unexpected token (14:21)
File was processed with these loaders:
 * ./node_modules/string-replace-loader/index.js
You may need an additional loader to handle the result of these loaders.
| export default class Users  {
| 
>     static myVar = 'users';
|    
| 
 @ ...

Unexpected output with webpack2

The code below will assign the created RegExp to options.search, in webpack2, the options.search will be reused for next file processing. So, the RegExp will be another one other than the first one expected.

function processOptions(source, options) {
  if (!_.isUndefined(options.search) && !_.isUndefined(options.replace)) {
    if (!_.isUndefined(options.flags)) {
      options.search = new RegExp(options.search, options.flags);
    }

    var newSource = source.replace(options.search, options.replace);
    if (options.strict && (newSource === source)) {
      throw new Error('Cannot replace ' + options.search + '' + options.replace);
    }
  } else if (options.strict) {
    throw new Error('Cannot replace: undefined search or/and option(s) → ' + JSON.stringify(options));
  }

  return newSource;
}

Strict mode: Error: Cannot replace x → y

I'm replacing some import in my scss file and it doesn't work:

Module build failed: Error: Cannot replace default-theme → client1
   at processOptions (/tmp/app/node_modules/string-replace-loader/index.js:12:13)
   at Object.module.exports (/tmp/app/node_modules/string-replace-loader/index.js:32:14)

here is the config:

       {
          test: /styles\.scss$/,
          use: [
            {
              loader: 'string-replace-loader',
              options: {
                search: 'default-theme',
                replace: 'foo-theme',
                strict: true
              }
            }
          ]
        }

Cannot supply flags when constructing one RegExp from another

Configuration

module.exports = {
  // ... 
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'string-replace',
        query: {
          multiple: [
             { search: '{vars.id}', replace: '90', flags: 'g' },
             { search: '{path.api}', replace: 'http://localhost:9000', flags: 'g'}
          ]
        }
      }
    ]
  }
}

Error:

WARNING in <file_name>
Module build failed: TypeError: Cannot supply flags when constructing one RegExp from another
    at new RegExp (native)
    at processOptions (node_modules/string-replace-loader/index.js:8:24)
    at node_modules/string-replace-loader/index.js:31:16
    at Array.forEach (native)
    at Object.module.exports (node_modules/string-replace-loader/index.js:29:22)
 @ ./src/javascript/scripts \.js$

This seems to be happening because https://github.com/Va1/string-replace-loader/blob/master/index.js#L29 returns source as regular expression, and then the regular expression is again passed to RegEx constructor at https://github.com/Va1/string-replace-loader/blob/master/index.js#L7

Workaround

For now, changing the configuration to following seems to work:

module.exports = {
  // ... 
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'string-replace',
        query: {
          multiple: [
             { search: new RegExp('{vars.id}', 'g'), replace: '90'},
             { search: new RegExp('{path.api}', 'g'), replace: 'http://localhost:9000'}
          ]
        }
      }
    ]
  }
}

Notice the multiple array using search option as RegExp instead of plain string without flags option.

Double quotation marks string replace issue

Hello,
I am trying to remove the following string @charset "UTF-8"; from Webpack's css output.
I am using the following configuration:

          loader: 'string-replace-loader',
          query: {
            multiple: [
              {
                search: '@charset "UTF-8";', 
                replace: '_____AAAAA_____',
                flags: 'ig'
              }              
            ]
          }

but it does not seems to work, unfortunately.
I noticed the following webpack log on my terminal:

"search":"@charset /"UTF-8/";","replace":"_____AAAAA_____","flags":"ig"

I guess something's wrong with the way the regexp is created, since it appends slashes, building up a wrong string that does not exists in my css.

Any idea?
Thanks

Webpack peer dependency in v1.0.5

I forked and cloned angular2-webpack-starter and after I started playing with it, I get the following warning all the time:

npm WARN [email protected] requires a peer of webpack@1 || 2 || ^2.0.0-beta || ^2.1.0-beta but none was installed.

I have webpack 2.2.0-rc.4 in dev dependencies. Should I downgrade or should the loader v1.0.5 be less picky?

Getting an unexpected token error when trying to process .json files

I've got some language translation files, I was hoping to parse them but when I include .json in the test regex I get an unexpected token error, you may need an appropriate loader to handle this file type

WARNING in ./src/client/locales/or-IN.json Module parse failed: Unexpected token (2:8) You may need an appropriate loader to handle this file type. | { | "hero": "Ensuring compensation for the creators of value", | "search": "Search", | "search_placeholder": "Search...", @ ./src/client/locales lazy ^\.\/.*$ @ ./src/client/translations/index.js @ ./src/client/index.js @ multi (webpack)-dev-server/client?http://localhost:3456 ./src/client/index.js

How can I get a file name in the replace fn?

I is it possible to retrieve information about the file context where the replace is happening? Just like this:

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'string-replace-loader',
        options: {
          search: '%%FILE_PATH%%',
          replace(match, p1, offset, string) {
            // Is there a way to get FULL_FILE_PATH like `/src/components/button.js?
            // the file that match rule's test 
            return FULL_FILE_PATH;
          },
          flags: 'g'
        }
      }
    ]
  }
}

No support for webpack 3.X

Getting the following error when npm installing:

npm WARN [email protected] requires a peer of webpack@1 || 2 but none was installed.

(I don't feel anything wrong/not working, so this seems easy to fix)

Как заменить подстроку в строке в файле HTML в Webpack 5

Здравствуйте Валентин,
Решил попробовать ваш лоадер, но столкнулся с проблемой.
Пусть у нас в HTML файле есть строка с псевдонимом <img src="@img/logo.jpg" alt="">
Я хочу псевдоним @img/ заменить на реальный путь, например img/
В конфигурационном файле webpack.config.js прописал следующее:

module: {
        rules: [
            {
                test: /\.html$/i,
                loader: 'string-replace-loader',
                options: {
                    search: /@img\//g,
                    replace: 'img/',
                    strict: true
                }
            },
          ]
   }

после команды npm run build (webpack --node-env=production)
в консоли появляется строка

[info] Working on 1 .html files (это после того как я прописал strict: true)
(node:8336) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated.
BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
        Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
        Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.
(Use "node --trace-deprecation ..." to show where the warning was created)
...
./src/img/logo.jpg 42 bytes (javascript) 154 KiB (asset) [built] [code generated]

Но как видно Webpack выгрузил изображение из html файла.

Если убрать правило string-replace-loader из модулей конфига, то получаю ошибку

ERROR in ./src/index.html 3:33-76
Module not found: Error: Can't resolve './@img/logo.jpg' in 'D:\Web\template\WebpackTemplate\src'
resolve './@img/logo.jpg' in 'D:\Web\template\WebpackTemplate\src'
  using description file: D:\Web\template\WebpackTemplate\package.json (relative path: ./src)
    using description file: D:\Web\template\WebpackTemplate\package.json (relative path: ./src/@img/logo.jpg)
      no extension
        D:\Web\template\WebpackTemplate\src\@img\logo.jpg doesn't exist
      as directory
        D:\Web\template\WebpackTemplate\src\@img\logo.jpg doesn't exist
 @ ./src/index.js 1:0-22

Callback replace not working

Hello !
I'm having lots of troubles having the callback replace working.
I put logs in many places and i'm tempted to say it may come either from schema-utils or loader-utils or ajv-keyword modules but i'm very new to webpack plugins so i can't tell for sure.

If i add this log in replace.js

  console.log("\nSEARCH :: ", search, replace);
  const newSource = source.replace(search, replace)

I also added a log on getOptionsArray.js :

  const rawOptions = getOptions(config)
  console.log(rawOptions);

And the "replace" field is simply missing from the log.
The search and flags keys are here.

If the replacement is a string the logs show the replacement properly, if the replacement is a fucntion, i get "null" everytime, except once sometimes at the end of the build.

This works :

multiple: [
	   {
		search: 'hello',
		flags: 'gi',
		replace: 'test'
	   },
]

This does not :

multiple: [
	   {
		search: 'hello',
		flags: 'gi',
		replace: function(match, p1, offset, string) {
			return "test";
		},
	},
]

Sometimes when i close the project (vscode), kill the node processes, and try to build again, the callback is passed properly everytime. But this happens very very randomly. It seems like there's also a compile cache somewhere that blocks the plugin's call or something.
I never put my hands inside webpack so i may be missing a thing.

Any idea what could be the reason of this?

Webpack 4 - Replace values inside json file

Hello everyone,

I am using Webpack 4.46.0 with "string-replace-loader" 2.3.0.

I am not able to replace any strings in my *.json files. I have various "app.json" files in different folders - therefore I want to replace some values inside.

Config:

 module: {
    rules: [
      {
        test: /app\.json$/,
        loader: 'string-replace-loader',
        options: {
          multiple: [
            { search: './data_a', replace: '../../data_a', flags: 'g'},
            { search: './data_b', replace: '../../data_b', flags: 'g' },
          ],
        },
      },

Any ideas what I am doing wrong?

DeprecationWarning: loaderUtils.parseQuery()

Hi there, today we start getting an deprecation warning which is caused by using parseQuery() method. Here is a full text of warning:
node : (node:2124) DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic, see webpack/loader-utils#56
At line:1 char:1

CategoryInfo          : NotSpecified: ((node:2124) Dep...utils/issues/56:String) [], RemoteException
FullyQualifiedErrorId : NativeCommandError
parseQuery() will be replaced with getOptions() in the next major version of loader-utils.

Add RegExp type search.

Now only string types are supported. Apparently, It would be fairly easy to add RegExp type to schema.

Replace string only on plain text

I'm trying to use this loader on templates, but the problem is that the loader is replacing the name of tags, classes, id and others.

I wanna to persist this changes only on plain text.

Sourcemaps seem to break when replacing "ngInject" prologues.

I noticed if I use this loader to replace the "ngInject"; prologues my source maps no longer open the original file.

{
	loader: 'string-replace-loader',
	options: {
		multiple: [
			{
				search: /["']ngInject["'];*/,
				replace: '',
				flags: 'g'
			}
		]
	}
},
{
    loader: 'ng-annotate-loader'
},
{
	loader: 'babel-loader',
	options: {
		cacheDirectory: true
	}
},

Perhaps I'm missing something? If I take out the string-replace-loader source maps are okay again.

flags: 'g' not working

Hi

I've been trying to get string-replace-loader to work with the 'g' flag.

...

    loader: 'string-replace-loader',
    query: {
      search: 'REST_API',
      replace: 'test',
      flags: 'g'
    }

That doesn't seem to work out. If I remove the 'g' flag and set '' or 'i' as flag, it works perfectly. But 'g' flag always brings back the following error:

ERROR in ./~/css-loader?sourceMap!./~/vue-loader/lib/style-compiler?{"id":"data-v-84da6350","scoped":false,"hasInlineConfig":false}!./~/vue-loader/lib/selector.js?type=styles&index=0!./~/string-replace-loader?{"search":{},"replace":"test","flags":"g"}!./src/components/something/Test.vue
Module build failed: TypeError: Cannot read property 'content' of undefined
    at Object.module.exports (/home/inzanez/WebDevel/testapp/node_modules/vue-loader/lib/selector.js:18:27)
 @ ./~/vue-style-loader!./~/css-loader?sourceMap!./~/vue-loader/lib/style-compiler?{"id":"data-v-84da6350","scoped":false,"hasInlineConfig":false}!./~/vue-loader/lib/selector.js?type=styles&index=0!./~/string-replace-loader?{"search":{},"replace":"test","flags":"g"}!./src/components/something/Test.vue 4:14-409 13:3-17:5 14:22-417
 @ ./src/components/something/Test.vue
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js

Any idea what might be wrong here?oO

Feature request: callbacks

Would be great if I could specify a callback function as a replacement like:

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'string-replace-loader',
        options: {
          search: 'my name',
          replace: function(result){
                  return result.toUpperCase();
          },
          flags: 'gi'
        }
      }
    ]
  }
}

I am unable to use this. I want chnage assets path in generated js file in build.

I am unable to use this. I want change assets path in generated js file in build. Please provide me detail steps to implement this.

Currently, I have added below code in webpack.dev.js file.

module: {
loaders: [
{
test: /.*/,
loader: 'string-replace',
query: {
search: 'locales',
replace: 'bankim',
},
exclude: /node_modules/
}
],

And use npm install --save-dev string-replace-loader

Let me know if I miss something.

it not works! I want to replace dev code in prod env!

it not works! I want to replace dev code in prod env!

// Add a response interceptor
axios.interceptors.response.use(function (response) {
  //@replaceStart
  // Do something with response data
  response.key = '1104'//just for dev code
  //@replaceEnd
  return response;
}, function (error) {
  // Do something with response error

  return Promise.reject(error);
});

webpack.js

  {
        test: /\.js$/,
        loader: "string-replace-loader",
        options: {
          search: "@replaceStart[\w\W\s]*?@replaceEnd",
          replace: "",
          flags: 'g'
        }
      },

or

{
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [
          'babel-loader',
          {
            // test: /\.js$/,
            loader: "string-replace-loader",
            options: {
              search: "@replaceStart[\w\W\s]*?@replaceEnd",
              replace: "",
              flags: 'g'
            }
          }
        ]
      },

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.