Angular 2构建后自定义index.html存放位置的实现方法
好问题!针对你想把Angular构建后的index.html放到Django templates文件夹的需求,我来给你梳理几种可行的方案:
1. 直接通过Angular CLI配置(分版本适配)
针对Angular 6+(使用angular.json)
新版本的Angular CLI已经支持直接配置index.html的输出路径,你只需要在项目根目录的angular.json里找到对应项目的build配置,修改index字段即可:
"projects": { "your-project-name": { "architect": { "build": { "options": { "outputPath": "dist", "index": { "input": "src/index.html", "output": "../templates/main/index.html" }, // 保留其他原有配置(如styles、scripts等)... } } } } }
这里的output路径是相对于outputPath(默认是dist文件夹)的,所以../templates/main/index.html会把最终的index.html生成到项目根目录下的templates/main文件夹里,正好匹配你的Django需求。
针对Angular 5及以前(使用angular-cli.json)
老版本的Angular CLI没有直接提供修改index输出路径的配置项,因为它封装了Webpack的细节。如果不想改动核心配置,更推荐用后面的构建后脚本方案;如果一定要通过Webpack配置实现,你需要先执行ng eject命令导出Webpack配置文件,然后在导出的webpack.config.js里修改HtmlWebpackPlugin的filename参数,就像你提到的那样:
new HtmlWebpackPlugin({ template: "./src/index.html", filename: "../templates/main/index.html", // 保留其他默认配置项... })
不过要注意,ng eject之后就无法再使用Angular CLI的默认构建命令了,需要自己维护Webpack配置,后续CLI升级也会受影响,所以这个方案要谨慎选择。
2. 构建后脚本(最省心的方案)
你已经尝试过用cp命令复制文件,其实可以把这个操作自动化,放到package.json的脚本里,这样每次构建完成后会自动执行复制操作:
跨平台通用方案(推荐)
先安装跨平台的文件复制工具cpy-cli:
npm install cpy-cli --save-dev
然后修改package.json的scripts字段:
"scripts": { "build": "ng build", "postbuild": "cpy dist/index.html ../templates/main/" }
之后你只需要执行npm run build,构建完成后就会自动把index.html复制到目标位置,Windows、Linux、macOS都能正常运行。
单一平台方案
如果只在Linux/macOS环境下开发,直接用系统自带的cp命令即可:
"scripts": { "build": "ng build", "postbuild": "cp dist/index.html ../templates/main/index.html" }
如果是Windows环境,把cp换成copy:
"scripts": { "build": "ng build", "postbuild": "copy dist\\index.html ..\\templates\\main\\index.html" }
总结
如果是新版本Angular,直接修改angular.json的配置最直接;如果是老版本或者不想改动CLI核心配置,构建后脚本是最稳妥的选择,既不会影响CLI的正常使用,也能满足你的自定义路径需求。
内容的提问来源于stack exchange,提问作者Abhishek Agarwal

