1 Star 0 Fork 0

amiko / articles

Create your Gitee Account
Explore and code with more than 6 million developers,Free private repositories !:)
Sign up
This repository doesn't specify license. Without author's permission, this code is only for learning and cannot be used for other purposes.
Clone or download
gulp_preprocess.md 1.84 KB
Copy Edit Web IDE Raw Blame History
caihaifei authored 2021-03-16 09:29 . update.

Gulp 通过gulp-preprocess实现简单的环境配置部署

通过Gulp可以对于前端代码进行一个代码的多页面构建,避免不必要的重复性工作,提高代码的可读性,为了实现通过参数控制不同环境的打包编译,我们引入了gulp-preprocess插件,该插件在gulp代码编译期间就实现了分环境配置的功能。

配置

  1. 安装gulp-preprocess插件
$ yarn add -D gulp-preprocess 
# or
$ npm install --save-dev gulp-preprocess 
  1. gulpfile.js配置
const preprocess = require('gulp-preprocess');

......
/* 打包babel的js文件 */
gulp.task('js:dev', async function () {
  return await gulp.src(['src/js/**/*.js'])
    .pipe(preprocess({
      context: {
        // 此处可接受来自调用命令的 NODE_ENV 参数,默认为 development 开发测试环境
        NODE_ENV: process.env.NODE_ENV || 'development',
      },
    }))
    .pipe(babel())
    .pipe(uglifyJs())
    .pipe(gulp.dest('dist/js'))
})

gulp.task('dev', gulp.series(gulp.parallel('js:dev', 'css:dev', 'img:dev',  'html:dev'), function (done) {
  done()
}))
  1. package.json 添加脚本配置

...
  "scripts": {
    "dev": "gulp dev",
  },

...

添加配置文件

//config.js gulp-preprocess 通过注解方式实现了编译配置

var config = {
    // @if NODE_ENV = 'production'
    apiUrl:'http://production.api.cn',
    // @endif
    // @if NODE_ENV = 'development'
    apiUrl:'http://development.api.cn',
    // @endif
}

window.config = config;


//request.js
 $.ajax({
    type: "POST",
    dataType: "json",
    url: config.apiUrl + url,
    success: function (res) {
        console.log('请求成功:',res)
    },
    error: function (error) {
            console.log('请求失败:',error)
    },
    });

运行

$yarn run dev
#or
$npm run dev

Comment ( 0 )

Sign in for post a comment

1
https://gitee.com/amiko/articles.git
git@gitee.com:amiko/articles.git
amiko
articles
articles
master

Search

102255 3a0e046c 1850385 102255 7aaa926c 1850385