将 VueJS 3 应用程序构建为单个 ES 模块包?

Build VueJS 3 application as a single ES Module bundle?

我有一个 Vue3 项目,我用打字稿和一个 main.ts 入口文件配置了一个默认导出。

import { App, createApp } from "vue";
import { createIntl } from "vue-intl";

import Application from "./App.vue";
import { AppProps, Settings } from "types";

let appRef = {} as App<Element>;

const AppLifecycle = {
  mount: (container: HTMLElement, appProps: AppProps, settings: Settings) => {
    const { themeUrl, userPreferences } = settings;
    const { language } = userPreferences;

    appRef = createApp(Application, { ...appProps, themeUrl });
    appRef.use(
      createIntl({
        locale: language,
        defaultLocale: "en",
        messages: messages[language],
      })
    );
    appRef.mount(container);
  },
  unmount: (_: HTMLElement) => {
    appRef.unmount();
  },
};

export default AppLifecycle;

我想将其构建为单个 ES 模块包,以便将其集成到具有以下要求的私有平台中:

the app’s bundle must be a JavaScript ES Module;

the default export of the app must be an object to handle the app’s lifecycle (the AppLifecycle object above)

从样板项目(用 React + Typescript 编写)中,他们使用以下 webpack 配置:

const path = require("path");

module.exports = {
  mode: "production",
  entry: "./src/index.tsx",
  experiments: {
    outputModule: true,
  },
  output: {
    filename: "main.js",
    path: path.resolve(__dirname, "dist"),
    library: {
      type: "module",
    },
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: "css-loader",
      },
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
    ],
  },
};

据我了解,Vue3 在后台使用 webpack4,并且可以在一定程度上调整配置,使用内部的 webpack 链 vue.config.js。此外,vue-cli 可用于指定目标(例如 --target lib),但我认为这种方式不支持 ES 模块。我尝试使用以下配置,但我不知道这是否正确。

module.exports = {
  chainWebpack: (config) => {
    config.optimization.set("splitChunks", false);
    config.plugins.delete("prefetch");
    config.plugins.delete("preload");
  },
  css: {
    extract: false,
  },
  filenameHashing: false,
};

我没有找到任何关于如何使用 Vue3 使用单个打字稿入口文件专门构建单个 ES 模块的详细资源,所以我在这里问。提前致谢。

我通过将 vue-cli 升级到版本 5 解决了这个问题,在各种更改中考虑了处理 ES 模块生成的 Webpack 5 https://next.cli.vuejs.org/migrations/migrate-from-v4.html#webpack-5

我已经更改了 vue.config.js 文件以符合我发布的样板文件。像下面这样:

module.exports = {
  configureWebpack: {
    entry: "./src/main.ts",
    experiments: {
      outputModule: true,
    },
    optimization: {
      splitChunks: false,
    },
    output: {
      library: {
        type: "module",
      },
    },
  },
  chainWebpack: (config) => {
    config.plugins.delete("prefetch");
    config.plugins.delete("preload");
  },
  css: {
    extract: false,
  },
  filenameHashing: false,
};

我更喜欢这个解决方案,而不是像 Estus Flask 建议的那样使用 Vite,因为我不知道该工具,而且我更喜欢坚持使用与目标平台相同的 Webpack。