Gulp是一个基于流的自动化构建工具,而AngularJS是一个前端MVC框架。在开发过程中,有时需要让AngularJS服务访问Gulp构建过程中定义的变量或配置。
const gulp = require('gulp');
const fs = require('fs');
gulp.task('generate-config', function() {
const config = {
apiUrl: process.env.API_URL || 'https://api.example.com',
buildVersion: new Date().getTime(),
debugMode: true
};
fs.writeFileSync('./src/app/config.json', JSON.stringify(config));
});
angular.module('myApp').factory('AppConfig', ['$http', function($http) {
return $http.get('app/config.json').then(function(response) {
return response.data;
});
}]);
npm install gulp-ng-config --save-dev
const ngConfig = require('gulp-ng-config');
gulp.task('config', function() {
gulp.src('config.json')
.pipe(ngConfig('myApp.config', {
environment: 'development'
}))
.pipe(gulp.dest('src/app'));
});
angular.module('myApp')
.controller('MyCtrl', ['config', function(config) {
console.log(config.apiUrl);
}]);
const gulp = require('gulp');
const replace = require('gulp-replace');
gulp.task('inject-config', function() {
return gulp.src('src/index.html')
.pipe(replace('<!-- CONFIG -->', `
<script>
window.APP_CONFIG = {
apiUrl: '${process.env.API_URL}',
buildDate: '${new Date().toISOString()}'
};
</script>
`))
.pipe(gulp.dest('dist'));
});
angular.module('myApp').factory('ConfigService', [function() {
return {
get: function(key) {
return window.APP_CONFIG ? window.APP_CONFIG[key] : null;
}
};
}]);
原因:Gulp任务未正确执行或缓存问题 解决:
gulp-clean
或del
插件清理目标目录原因:JSON配置文件请求可能被浏览器阻止 解决:
原因:环境变量未正确传递 解决:
dotenv
加载.env文件通过以上方法,您可以有效地在AngularJS服务中访问Gulp构建过程中定义的变量,实现构建时配置与运行时应用的完美结合。
没有搜到相关的文章