【问题标题】:jQuery plugin grunt build change webservice urlsjQuery 插件 grunt 构建更改 web 服务 url
【发布时间】:2015-05-28 14:24:25
【问题描述】:

快速提问,

我有一个使用 Grunt 的 jquery 插件,现在在我的 js 文件中列出了一个 web 服务,即

//webservice settings
api_endpoint: "http://localhost/api/v1"

这在我的开发中很好,但是当我得到 prod 时,我希望将其更改为 i.e.

api_endpoint: "http://prod/api/v1"

我的 Grunt 文件看起来像这样

    // Concat definitions
    concat: {
        options: {
            banner: "<%= meta.banner %>"
        },
        dist: {
            src: ["src/jquery.myPlugin.autocomplete.js", "src/jquery.myPlugin.tabs.js", "src/jquery.myPlugin.clearsearch.js", "src/jquery.myPlugin.v2.0.js"],
            dest: "dist/jquery.myPlugin.v2.0.js"
        }
    },

    // Lint definitions
    jshint: {
        files: ["src/jquery.myPlugin.v2.0.js"],
        options: {
            jshintrc: ".jshintrc"
        }
    },

    // Minify definitions
    uglify: {
        my_target: {
            src: ["dist/jquery.myPlugin.v2.0.js"],
            dest: "dist/jquery.myPlugin.v2.0.min.js"
        },
        options: {
            banner: "<%= meta.banner %>"
        }
    },

grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-variablize');
grunt.loadNpmTasks("grunt-contrib-concat");
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-contrib-uglify");
grunt.loadNpmTasks("grunt-contrib-sass");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-copy');

grunt.registerTask("build", [
    "clean:pre",
    "concat",
    "uglify",
    "cssmin",
    "copy",
    'clean:post',
    "watch"
]);

【问题讨论】:

    标签: jquery plugins build gruntjs


    【解决方案1】:

    使用grunt-replace

    设置配置

    replace: {
        api: {
            options: {
                patterns: [
                    {
                        match: '/http://localhost/api/v1/g',
                        replacement: 'http://prod/api/v1'
                    }
                ]
            },
            files: [
                {
                    expand: true, 
                    flatten: true, 
                    src: ['dist/jquery.myPlugin.v2.0.js'], 
                    dest: 'dist/'
                }
            ]
        }
    }
    

    加载包

    grunt.loadNpmTasks('grunt-replace');
    

    添加分发任务

    // This could be done better, but just example
    grunt.registerTask("dist", [
        "clean:pre",
        "concat",
        "replace:api",
        "uglify",
        "cssmin",
        "copy",
        'clean:post',
        "watch"
    ]);
    

    然后运行任务

    grunt dist
    

    【讨论】:

    • 收到错误无法替换没有@@的字符串
    • 对不起。它必须是正则表达式模式。您还可以将端点 url 替换为 @@API_ENDPOINT 并将 match 替换为 API_ENDPOINT。但这意味着您也必须在 build 任务中替换它。
    猜你喜欢
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 2011-02-12
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多