va1 / string-replace-loader Goto Github PK
View Code? Open in Web Editor NEWReplace loader for Webpack
License: MIT License
Replace loader for Webpack
License: MIT License
In string-replace-loader/lib/getOptionsArray.js
, line 13,
type: 'string'
should read
types: ['string', 'function']
This would allow for template functions to be used for the replace value.
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
module.exports = {
module: {
rules: [
{
test: /fileInWhichJQueryIsUndefined\.js$/,
loader: 'string-replace-loader',
options: {
search: '$',
replace: 'window.jQuery',
}
}
]
}
}
DefinePlugin
module.exports = {
plugins: [
new webpack.DefinePlugin({
$: 'window.jQuery'
})
]
}
I use string-replace-loader to replace assetspath both in html and js.
It works in html, but fails in js.
this is my code:
{ loader: 'string-replace-loader', options: { search: '"\/images\/', replace: '"' + config.publicPath + 'images/', flags: 'ig' } }
{
loader: 'string-replace-loader',
options: {
search: '__SMALL_VIEW_MEDIA_QUERY__',
replace: `max-width: ${webpackCompileTimeVars.smallViewMaxWidth}px`
}
}
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?
I am trying to search and replace in a CSS file without any success. Please confirm if I can search and replace text in a case file or this is a bug.
If you have multiple loaders, you won't be able to use this loader. You will receive the error message:
Error: Cannot define 'query' and multiple loaders in loaders list
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';
|
|
@ ...
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;
}
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
}
}
]
}
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'}
]
}
}
]
}
}
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
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.
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
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?
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
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'
}
}
]
}
}
Getting the following error when npm install
ing:
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)
{
test: /NotifyRules\.js$/,
loader: 'string-replace-loader',
options: {
search: '$VERSION',
replace: 'hello',
strict:true
}
},
For your documentation, webpack gives this message:
BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.
You need to specify 'string-replace-loader' instead of 'string-replace',
see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed
Hello, i'm using Concat Plugin (https://www.npmjs.com/package/webpack-concat-plugin) to concat files in webpack, but i need replace strings in this files.. why dont work? string replace works only a webpack entry?
I expected plain replacement to match all instances.
Workaround: pass flags: 'g'
for regex global match.
Здравствуйте Валентин,
Решил попробовать ваш лоадер, но столкнулся с проблемой.
Пусть у нас в 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
I'm trying to replace my hashed bundle names in my templates and was wondering if I can accomplish it with this loader? :)
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?
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?
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.
Now only string types are supported. Apparently, It would be fairly easy to add RegExp type to schema.
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.
if the search string start with a '.' as in .html the .should be escaped in the the regex because it has a different meaning
Time to update peerDependencies for webpack 3? :)
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.
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
{
test: /\.js$/,
loader: 'string-replace-loader',
options: {
search: /__\w{6}\b/g,
replace: function () {
return `${current filename? or pathname?}`; // this.resourcePath ?
},
},
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 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.
module.exports = {
// ...
module: {
rules: [
{
test: /image\/*$/,
loader: 'string-replace-loader',
options: {
// search: '$', disable search
replace:(content)=> {
maps.forEach(item => {
content = content.replace(item, `${cdn}${item}`)
})
return content;
},
}
}
]
}
}
string-replace-loader/lib/replace.js
Line 18 in 5423860
Looks like even with 2668cda people have warnings of missing webpack. That is the reason there is a forked repo at https://github.com/gdi2290/string-replace-loader . Any chance we can use the any webpack version?
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'
}
}
]
},
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.