URL 地址的参数化取决于 webpack 的构建配置文件
Parameterization of URL address depending on build profile by webpack
是否可以根据 webpack 构建配置文件进行参数化 URL?我说的是 URL 服务从 API 获取数据。例如,我在我的 Angular2 应用程序中有:
部分package.json:
"scripts": {
"build-prod": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail",
"build-dev": "rimraf dist && webpack --config config/webpack.dev.js --progress --profile --bail"
},
部分webpack.dev.js:
output: {
path: helpers.root('dist'),
publicPath: 'http://localhost:8080/',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
部分webpack.prod.js:
output: {
path: helpers.root('dist'),
publicPath: '/',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
和示例性的一部分 exampleService.ts:
API_URL = "some/address/for/me";
get(url: string): Promise<T> {
return this.http.get(this.API_URL)
.toPromise()
.then(response => {//someCode})
.catch(this.handleError);
}
工作正常。但是,如果我将使用 dev 配置文件构建应用程序,我希望应用程序询问我的养蜂场(例如),而不是我的本地主机。我应该在哪里更改我的 webpack.dev.js?
抱歉我的英语不好。
exampleService.ts
中的webpackdefine-plugin
performs search and replace on basis of the source code. Use constants like PRODUCTION
or the npm de-facto standard process.env.NODE_ENV
选择APIURL使用
在您的 webpack 配置中应用 define-plugin
:
module.exports = {
/*...*/
plugins:[
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
};
我建议阅读 building for production 上的 webpack 指南。
注意:我认为在 API_URL
字符串 some/address/for/me
上使用插件也可能有效:new webpack.DefinePlugin({'some/address/for/me
可能':JSON.stringify('other/url') })`
是否可以根据 webpack 构建配置文件进行参数化 URL?我说的是 URL 服务从 API 获取数据。例如,我在我的 Angular2 应用程序中有:
部分package.json:
"scripts": {
"build-prod": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail",
"build-dev": "rimraf dist && webpack --config config/webpack.dev.js --progress --profile --bail"
},
部分webpack.dev.js:
output: {
path: helpers.root('dist'),
publicPath: 'http://localhost:8080/',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
部分webpack.prod.js:
output: {
path: helpers.root('dist'),
publicPath: '/',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
和示例性的一部分 exampleService.ts:
API_URL = "some/address/for/me";
get(url: string): Promise<T> {
return this.http.get(this.API_URL)
.toPromise()
.then(response => {//someCode})
.catch(this.handleError);
}
工作正常。但是,如果我将使用 dev 配置文件构建应用程序,我希望应用程序询问我的养蜂场(例如),而不是我的本地主机。我应该在哪里更改我的 webpack.dev.js?
抱歉我的英语不好。
exampleService.ts
中的webpackdefine-plugin
performs search and replace on basis of the source code. Use constants like PRODUCTION
or the npm de-facto standard process.env.NODE_ENV
选择APIURL使用
在您的 webpack 配置中应用 define-plugin
:
module.exports = {
/*...*/
plugins:[
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
};
我建议阅读 building for production 上的 webpack 指南。
注意:我认为在 API_URL
字符串 some/address/for/me
上使用插件也可能有效:new webpack.DefinePlugin({'some/address/for/me
可能':JSON.stringify('other/url') })`