【问题标题】:'ng build' move scripts to subfolder'ng build' 将脚本移动到子文件夹
【发布时间】: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


    【解决方案1】:
    1. 运行ng eject -ec(添加'-prod' 用于生产构建,或-aot false 用于JIT 构建)。此命令将在您的根目录中公开 webpack.config.js 文件。 -ec 标志将提取 CSS 文件(而不是从 JS 文件中提供它们)。 (要再次“取消拒绝”您的应用,请参阅我的 another answer
    2. 运行 npm install 以安装 webpack 加载器

    3. 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" }

    4. 因为我们在ng eject 命令中添加了-ec 标志,所以我们现在也有了CSS 文件。我们也可以通过修改 webpack.config.jsplugins 条目下的 ExtractTextPlugin 插件将其移动到 dist/styles文件:

      new ExtractTextPlugin({ "filename": "styles/[name].[contenthash:20].bundle.css", "disable": false }),

    5. 运行 npm run build,因为 ng build 不再适用于弹出的应用程序。 您应该获得 dist 目录,其中包含 scriptsstyles 目录以及它们的 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 版本的时间完美配合(我可能应该写这个版本作为回答)。如果您需要当前版本的.help,请指定此版本以及您的具体需求,我会尽力提供帮助
    【解决方案2】:

    您可以通过更改angular-cli.json 中的outDir 来更改dist 目录,但您不能为js 文件设置单独的目录。

    如果你想这样做,你必须编写一个在构建之后运行的小节点脚本,并将你想要的文件复制到dist/scripts。您还必须更改 index.html 中的 &lt;script&gt; 标记以指向新位置。

    【讨论】:

      最近更新 更多