AngularJS 中的配置文件 [英] Configuration file in AngularJS
问题描述
创建配置文件(类似于 .net 中的 Web 配置)、用于存储 url 和其他在应用程序部署期间可能会发生变化的常量的最佳方法是什么?
使用 .constant()
方法:
angular.module('app').constant('MONGOLAB_CONFIG', {baseUrl: '/databases/',dbName: 'ascrum'});
就像这个例子.>
然后你可以将它注入你需要常量的地方.
你可以有不同的文件定义不同的常量用于开发或生产,然后使用像 Grunt 这样的工具根据环境使用这个或那个文件.
假设您有这种文件夹结构:
|-js/||-app.js||-anotherfile.js||-...||-环境/||-dev.js||-prod.js||-index.html
dev.js
和 prod.js
使用不同的值定义了相同的 .constant()
服务.然后你可以得到正确的文件,像这样的 gruntFile 连接起来:
grunt.registerTask('default', ['concat']);grunt.initConfig({环境:process.env.NODE_ENV,源代码:{javascript: ['js/*.js'],配置:['env/<%= env %>.js']},连接:{javascript: {src:['<%= src.config %>', '<%= src.javascript %>'],目标:'myapp.js'}}});
通过运行 grunt
你会得到一个 myapp.js
包含好的常量的文件.
编辑:使用 Gulp,您可以这样做:
var 路径 = ['env/' + process.env.NODE_ENV + '.js','js/**/*.js',];var stream = gulp.src(paths).pipe(plugins.concat('main.js')).pipe(gulp.dest('/输出'));
What is the best way to create config file (Something like web config in .net), for storing urls, and other constants that may vary during the application deploy?
Use the .constant()
method:
angular.module('app').constant('MONGOLAB_CONFIG', {
baseUrl: '/databases/',
dbName: 'ascrum'
});
like in this example.
Then you can just inject it where you need the constants.
You can have different files defining different constants for development or production, and then use a tool like Grunt to use this or that file according to the environment.
Let's assume you have this kind of folder structure:
|-js/
| |-app.js
| |-anotherfile.js
| |-...
|
|-env/
| |-dev.js
| |-prod.js
|
|-index.html
dev.js
and prod.js
defines the same .constant()
service with different values.
Then you can get the proper file to be concatenated with a gruntFile like that:
grunt.registerTask('default', ['concat']);
grunt.initConfig({
env : process.env.NODE_ENV,
src: {
javascript: ['js/*.js'],
config: ['env/<%= env %>.js']
},
concat: {
javascript: {
src:['<%= src.config %>', '<%= src.javascript %>'],
dest:'myapp.js'
}
}
});
By running grunt
you would get a myapp.js
file containing the good constants.
Edit: with Gulp you can do it like this:
var paths = [
'env/' + process.env.NODE_ENV + '.js',
'js/**/*.js',
];
var stream = gulp.src(paths)
.pipe(plugins.concat('main.js'))
.pipe(gulp.dest('/output'));
这篇关于AngularJS 中的配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!