【问题标题】:replace with regex for gulp-replace用正则表达式替换 gulp-replace
【发布时间】:2019-01-06 13:48:28
【问题描述】:

我正在使用 gulp replace 通过匹配起始和结束字符串将完整路径名替换为另一个名称

例子

输入:

src/app/Client/Home/home.service.js

输出

dist/Home/home.service.min.js


.state('masterPage.blogArticle', {
            url: "/article/:postId",
            templateUrl: "src/app/Client/Blog/article/index.html",
            controller: "articleCtrl",
            controllerAs: 'vm',
            resolve: {
                deps: ['$ocLazyLoad', function ($ocLazyLoad) {
                    return $ocLazyLoad.load({
                        name: 'competitiveClient',
                        insertBefore: '#ng_load_plugins_before', // load the above css files before a LINK element with this ID. Dynamic CSS files must be loaded between core and theme css files
                        files: [
                            'src/app/Client/Blog/article/article.service.js',
                            'src/app/Client/Blog/article/article.controller.js'
                        ]
                    });
                }]
            }
        })

这里我想在所有状态下用上面的输出替换 .js 文件路径


gulp.task('templates', () => {
  gulp.src(['dist/client/app/js/app.config.min.js'])
    .pipe(replace(/^(src\/app\/Client\/)(.*)(.js)$/g, 'dist/client/app'))
    .pipe(replace(/.js/g, '.min.js'))
    .pipe(gulp.dest('dist/client/app/js/'));
 });

但它不工作,它没有得到匹配的路径 所以如果有人有想法解决它。 提前致谢。

【问题讨论】:

  • 不清楚您在寻找什么。您要匹配的文件中的字符串是什么,替换后您希望最终字符串是什么?请编辑您的问题。
  • 您不是在尝试使用 gulp-replace 重命名文件本身吗?它只修改文件中的文本而不是文件名本身。
  • @Mark 我的字符串路径为“src/app/Client/Home/home.service.js”,我想用“dist/Home/home.service.min.js”替换字符串并且有许多具有相同模式的字符串路径
  • 好的,我编辑了答案 - 我被你的代码“dist/client/app”中的替换字符串弄糊涂了。
  • @Mark 谢谢,但这仍然不起作用,但我已经尝试过这个“ /src\/app\/Client\/(.*?)\.*\.js/ig ”它正在工作但它只替换所有内容而不是 .js 文件

标签: angularjs gulp gulp-uglify gulp-replace


【解决方案1】:

试试:

gulp.task('templates', () => {

  return gulp.src(['dist/client/app/js/app.config.min.js'])

      // need the matching groups 2 and 3 as well, and the m flag

      //.pipe(replace(/^(src\/app\/Client\/)(.*)(.js)$/gm, 'dist/$2$3'))

      .pipe(replace(/(src\/app\/Client\/)(.*)(.js)/g, 'dist/$2$3'))

      // escape the .
      .pipe(replace(/\.js/g, '.min.js'))

      .pipe(gulp.dest('dist/client/app/js/'));
});

src/app/Client/Home/home.service.js

==>

dist/Home/home.service.min.js

[你也会想要我在那里添加的 return 语句。]

【讨论】:

  • 不工作它没有找到带有正则表达式的字符串,它用字符串替换了 dist/client/app/$2$3
【解决方案2】:

根据this answergulp-replace 将回调作为第二个参数。唯一的技巧是完整匹配将是第一个参数,所有匹配组将是第二个到第 n 个参数,然后还有更多。

例如

replace("my-(.*)", (full, capture) => {return "string: " + capture}) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    相关资源
    最近更新 更多