Webpack/Angular CLI - 如何在 HTML 中嵌入脚本而不是引用它们?

Webpack/Angular CLI - how to embed scripts in HTML instead of referencing them?

我正在构建一个精简的 Angular 应用程序,它应该是 运行 通过 file:// URL 本地化的应用程序。 index.html 文件将通过无头浏览器附加和部署,我无法使用 HTTP 服务器作为解决方案。 运行 本地文件会出现跨源错误,如 here 所述。

我提出的有效 (!) 解决方案是将所有 <script src="..."/> 资源(与 ng build --prod 捆绑在一起)替换为 <script>...</script>。目前,我正在手动

我的 ng build 的输出 index.html 是:

<script src="runtime-es2015.1eba213af0b233498d9d.js" type="module"></script><script src="runtime-es5.1eba213af0b233498d9d.js" nomodule defer></script><script src="polyfills-es5.9e286f6d9247438cbb02.js" nomodule defer></script><script src="polyfills-es2015.690002c25ea8557bb4b0.js" type="module"></script><script src="main-es2015.3bdd714db04c3d863447.js" type="module"></script><script src="main-es5.3bdd714db04c3d863447.js" nomodule defer></script>

我正在将其更改为:

<script type="module">//content of runtime-es2015.1eba213af0b233498d9d.js//</script><script nomodule defer>//content of runtime-es5.1eba213af0b233498d9d.js//</script><script nomodule defer>//content of polyfills-es5.9e286f6d9247438cbb02.js//</script><script type="module">//content of polyfills-es2015.690002c25ea8557bb4b0.js//</script><script type="module">//content of main-es2015.3bdd714db04c3d863447.js//</script><script nomodule defer>//content of main-es5.3bdd714db04c3d863447.js//</script>

我正在寻找一种通过构建脚本使其自动化的方法。

谢谢。

这是我最终想出的解决方案 gulp:

我已经 运行 npm install --save-dev 打包了 gulpgulp-inlinedel.

在根目录创建gulpfile.js后,我写了下面的代码:

let gulp = require('gulp');
let inline = require('gulp-inline');
let del = require('del');

gulp.task('inline', function (done) {
    gulp.src('dist/index.html')
    .pipe(inline({
        base: 'dist/',
        disabledTypes: 'css, svg, img'
    }))
    .pipe(gulp.dest('dist/').on('finish', function(){
        done()
    }));
});

gulp.task('clean', function (done) {
    del(['dist/*.js'])
    done()
});

gulp.task('bundle-for-local', gulp.series('inline', 'clean'))

任务inline会将所有<script src="..."></script>替换为相应的文件内容。 clean 然后会删除所有 .js 文件。

最后,我用新的构建脚本更新了我的 package.json

"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "build-for-local": "ng build --prod --aot && gulp bundle-for-local",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },

现在 npm run build-for-local 将完成这项工作。