Vue Cli 3 排除 typescript 文件被注入 index.html

Vue Cli 3 exclude typescript file from being injected in index.html

我用 Vue Cli 创建了一个 typescript 项目。

我想要一个单独的 commands.html 文件,其中应包含来自 commands.ts 文件的 javascript 代码。

我把commands.html文件放在了public文件夹下,所以建工程的时候复制到dist文件夹下

commands.ts 文件在根文件夹中(在与 publicsrcnode_modules 等文件夹相同的文件夹中)。

Webpack 应该执行以下操作:

  1. 缩小 commands.html 文件(就像缩小 index.html 一样)
  2. commands.ts 文件编译为 JavaScript
  3. 将生成的JavaScript文件放入dist/js文件夹
  4. commands.html 文件中放置一个指向生成的 JavaScript 文件的脚本标签

我尝试了以下方法:

我安装了html-webpack-plugin

我使用以下代码创建了一个 vue.config.js 文件:

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  configureWebpack: {
    entry: {
      commands: './commands.ts',
    },
    plugins: [
      new HtmlWebpackPlugin({
        filename: 'commands.html',
        template: './public/commands.html',
        chunks: ['commands'],
        minify: {
          collapseWhitespace: true,
        },
      }),
    ],
  },
};

这一切都正确,但它还在 index.html 文件中创建了一个指向生成的 JavaScript 文件的脚本标记。我认为 Vue 的默认 Webpack 配置正在编译注入 index.html 文件的包中的 commands.ts。我怎样才能阻止它这样做?

发现:

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  configureWebpack: {
    entry: {
      functionFile: './functionFile.ts',
    },
    plugins: [
      new HtmlWebpackPlugin({
        filename: 'functionFile.html',
        template: './public/functionFile.html',
        chunks: ['functionFile'],
        minify: {
          collapseWhitespace: true,
        },
      }),
    ],
    devServer: {
      https: true,
    },
  },
  chainWebpack: (config) => {
    config
      .plugin('html')
      .tap((args) => {
        // eslint-disable-next-line no-param-reassign
        args[0].excludeChunks = ['functionFile'];
        return args;
      });
  },
};