【发布时间】:2026-01-20 07:50:01
【问题描述】:
ng build 将文件导出到 dist 文件夹,如下所示
index.html
main.bundle.js
styles.bundle.js
...
我希望脚本在子文件夹中
*index.html
scripts/main.bundle.js
scripts/styles.bundle.js
...*
我该怎么做?
【问题讨论】:
标签: angular angular-cli
ng build 将文件导出到 dist 文件夹,如下所示
index.html
main.bundle.js
styles.bundle.js
...
我希望脚本在子文件夹中
*index.html
scripts/main.bundle.js
scripts/styles.bundle.js
...*
我该怎么做?
【问题讨论】:
标签: angular angular-cli
ng eject -ec(添加'-prod' 用于生产构建,或-aot false 用于JIT 构建)。此命令将在您的根目录中公开 webpack.config.js 文件。 -ec 标志将提取 CSS 文件(而不是从 JS 文件中提供它们)。 (要再次“取消拒绝”您的应用,请参阅我的 another answer)运行 npm install 以安装 webpack 加载器
在 webpack.config.js 文件中编辑 output 条目并为 JS 文件添加所需的目录名称:
"output": {
"path": path.join(process.cwd(), "dist"),
"filename": "scripts/[name].[chunkhash:20].bundle.js",
"chunkFilename": "scripts/[id].[chunkhash:20].chunk.js"
}
因为我们在ng eject 命令中添加了-ec 标志,所以我们现在也有了CSS 文件。我们也可以通过修改 webpack.config.js 中 plugins 条目下的 ExtractTextPlugin 插件将其移动到 dist/styles文件:
new ExtractTextPlugin({
"filename": "styles/[name].[contenthash:20].bundle.css",
"disable": false
}),
运行 npm run build,因为 ng build 不再适用于弹出的应用程序。
您应该获得 dist 目录,其中包含 scripts 和 styles 目录以及它们的 JS/CSS 文件 index.html 应该直接位于 dist 下,并且包含正确的内容,例如:
<link href="styles/styles.d41d8cd98f00b204e980.bundle.css" rel="stylesheet"/>
<script type="text/javascript" src="scripts/inline.3d27fc24e48981450c35.bundle.js"></script>
更新:
自 Angular 7 以来,弹出命令已被禁用,因此此解决方案将不再有效 (see this related question)。
【讨论】:
您可以通过更改angular-cli.json 中的outDir 来更改dist 目录,但您不能为js 文件设置单独的目录。
如果你想这样做,你必须编写一个在构建之后运行的小节点脚本,并将你想要的文件复制到dist/scripts。您还必须更改 index.html 中的 <script> 标记以指向新位置。
【讨论】: