angular-cli:切换到webpack后环境文件替换中断(使用`ng eject`)

时间:2017-02-22 09:41:35

标签: webpack angular-cli

我决定对angular-cli使用扩展的webpack配置,所以我运行了命令ng eject

看起来除了环境文件替换之外,一切都正常工作,在angular-cli.json中指定:

"environmentSource": "environments/environment.ts",
  "environments": {
    "dev": "environments/environment.ts",
    "prod": "environments/environment.prod.ts"
  }

现在根本没有替换,它总是使用“environments / environment.ts”文件。

有没有办法让它在没有重大更改webpack配置的情况下工作?

还为angular-cli github项目创建了an issue

2 个答案:

答案 0 :(得分:7)

嗯..我必须写自己的解决方案

在webpack中,我更改了AotPlugin插件的配置:

hostReplacementPaths: {
  'environments/environment.ts': environmentFiles[NODE_ENV]
}

,当然还有environmentFiles

const environmentFiles = {
  'development': 'environments/environment.dev.ts',
  'staging': 'environments/environment.stag.ts',
  'production': 'environments/environment.prod.ts'
};

答案 1 :(得分:4)

更新5/24/2017

我发现在npm start的监视模式下我遇到了一个错误,因为环境文件交换类似于带有angular-cli的this issue

在npm start期间进行的任何重新编译都会产生此错误

ERROR in ./src/environments/environment
Module build failed: Error: ENOENT: no such file or directory, open 'C:\dev\(...)\src\environments\environment'
 @ ./src/main.ts 4:0-57
 @ multi (webpack)-dev-server/client?http://localhost:4200 ./src/main.ts

我能够绕过环境交换本地'通过更新AotPlugin进行构建,如下所示。

new AotPlugin({
  "mainPath": "main.ts",
  "hostReplacementPaths": isLocal? {} : {
    "./environments/environment": `${envFile}`
  },
  "exclude": [],
  "tsConfigPath": "src\\tsconfig.app.json",
  "skipCodeGeneration": !isAot
})

原始发布

在这里发布此内容,以帮助其他人努力工作。

我使用Stepan的技术变体,但不会替换主机路径。我在Windows上,所以我尝试了斜线,反斜杠,逃避斜线等。

直到我将实际的import语句与hostReplacementPath实际进行替换相匹配为止。

在我的main.ts文件中,我有这个导入语句

import { environment } from './environments/environment';

当我在webpack.config.js文件中使用该确切路径时,它终于起作用了,如下所示。 (注意我还在环境字符串值上使用了字符串插值。



const environmentFiles = {
  'dev': 'environments/environment.dev.ts',
  'stage': 'environments/environment.stage.ts',
  'prod': 'environments/environment.prod.ts'
};

module.exports = function(env) {
  const isAot = env.aot || false;
  const isZip = env.zip || false;

  const isLocal = env.target === 'local';
  const envFile = environmentFiles[env.target];

// ... code omitted for brevity

new AotPlugin({
  "mainPath": "main.ts",
  "hostReplacementPaths": {
    "./environments/environment": `${envFile}`
  },
  "exclude": [],
  "tsConfigPath": "src\\tsconfig.app.json",
  "skipCodeGeneration": !isAot
})




最后,为了完整性,这是我的实际npm脚本

"build-prod-aot": "rimraf dist && webpack --env.target=prod --env.zip --env.aot --colors",
相关问题