Module has been externalized for browser compatibility error in Vite build
Asked Answered
D

3

14

I am currently working on a project that utilizes Vite version 4.3.2 and is integrated with Adobe Experience Manager (AEM) via the aem-vite plugin. The project also includes '@aem-vite/vite-aem-plugin' and '@aem-vite/import-rewriter'.

The issue I'm facing is that the project works fine on the dev server but throws an error when I build for production. The error message I get in the browser console is:

Module "" has been externalized for browser compatibility. Cannot access ".custom" in client code.

The Module "" part doesn't provide clarity on what actual module might be causing this issue.

Here is my entire vite.config.ts file:


    export default defineConfig(({ command, mode }) => ({
      plugins: [
        vue(),
        vueJsx(),
        tsconfigPaths(),
        viteForAem({
          contentPaths: [designsName, 'content'],
          publicPath: clientLibsPath,
        }),
        bundlesImportRewriter({
          publicPath: clientLibsPath,
          resourcesPath: 'resources/js',
        }),
        commonjs({
          include: '/node_modules/',
          requireReturnsDefault: 'auto',
          defaultIsModuleExports: 'auto',
        }),
      ],
      optimizeDeps: {
        include: ['qs', 'dayjs'],
      },
      resolve: {
        alias: {
          '@': fileURLToPath(new URL(clientScriptsPath, import.meta.url)),
          'aem-base': aemBaseClientPath(),
          ...createLibMock('lib/proxyImport', 'proxyImport'),
          ...createLibMock('components/mixins/isMobile', 'isMobile'),
          components: aemBaseClientPath('scripts/components'),
          constants: aemBaseClientPath('scripts/constants'),
          lib: aemBaseClientPath('scripts/lib'),
        },
        dedupe: ['vue'],
      },
      base: command === 'build' ? clientlibsFolderPath : '/',
      root: './',
      build: {
        brotliSize: false,
        manifest: false,
        minify: mode === 'development' ? false : 'esbuild',
        outDir: 'dist',
        sourcemap: command === 'serve' ? 'inline' : false,
        rollupOptions: {
          output: {
            assetFileNames: `${clientlibResourcesPath}/[ext]/[name][extname]`,
            chunkFileNames: `${clientlibResourcesPath}/chunks/[name].[hash].js`,
            entryFileNames: `${clientlibResourcesPath}/js/[name].js`,
          },
          input: {
            bundle: `${clientPath}/scripts/main.ts`,
            styles: `${clientPath}/assets/styles/main.scss`,
          },
        },
      },
      css: {
        preprocessorOptions: {
          scss: {
            additionalData: `$s-base-resource-path: "${aemBaseResourcePath}";$s-selectiontools-resource-path: "${clientLibsPath}";`,
            quietDeps: true,
          },
        },
        loaderOptions: {
          sass: {
            quietDeps: true,
          },
        },
      },
      test: {
        globals: true,
        environment: 'jsdom',
        exclude: [...configDefaults.exclude],
        root: `${clientScriptsPath}/tests`,
        coverage: {
          reporter: ['text', 'json', 'html', 'lcov'],
          reportsDirectory: `${testReportsPath}`,
        },
      },
    }));

Here is the section of my vite.config.js where I've set up aliases in an attempt to fix this:

resolve: {
alias: {
    process: "process/browser",
    buffer: "buffer",
    crypto: "crypto-browserify",
    stream: "stream-browserify",
    assert: "assert",
    http: "stream-http",
    https: "https-browserify",
    os: "os-browserify",
    url: "url",
    util: "util",
},

Despite this, I'm still receiving the same error.

I've already tried upgrading and downgrading the Vite version, but the issue persists. Is there something I'm missing or not understanding here? Any help would be greatly appreciated. Thank you.

Dunt answered 8/6, 2023 at 12:12 Comment(2)
you can try using the vite-plugin-node plugin. This plugin helps resolve the Node.js core modules automatically during the build process.Backsword
@Backsword thanks for the tip, but I am using AEM, so vite-plugin-node would probably not work.Dunt
H
12

Install vite-plugin-node-polyfills:

npm install --save-dev vite-plugin-node-polyfills

or yarn add --dev vite-plugin-node-polyfills

and add nodePolyfills() to vite.config.ts

export default defineConfig({
  plugins: [
    nodePolyfills(),
    ...
  ],
  ...
}

https://www.npmjs.com/package/vite-plugin-node-polyfills

Hellenistic answered 13/10, 2023 at 19:0 Comment(0)
D
2

You can avoid these warnings by using a polyfill node package like rollup-plugin-node-polyfills and use it in your alias settings:

    resolve: {
        alias: {
            util: "rollup-plugin-node-polyfills/polyfills/util",
            assert: "rollup-plugin-node-polyfills/polyfills/assert",
            os: "rollup-plugin-node-polyfills/polyfills/os",
            buffer: "rollup-plugin-node-polyfills/polyfills/buffer-es6",
            process: "rollup-plugin-node-polyfills/polyfills/process-es6",
            fs: "rollup-plugin-node-polyfills/polyfills/empty",
            net: "rollup-plugin-node-polyfills/polyfills/empty",
            perf_hooks: "rollup-plugin-node-polyfills/polyfills/empty",
            path: "rollup-plugin-node-polyfills/polyfills/path",
            child_process: "rollup-plugin-node-polyfills/polyfills/empty",
        },
    },

For non-existing polyfills or when you are sure the code that imports a specific Node.js module is never executed in the browser, use the empty "polyfill".

Distend answered 15/6, 2023 at 9:51 Comment(1)
Thanks. I have a lot of modules with dependencies for code paths I won't use - eg, old slow blockchains that I don't use, or node-specific code that I know will never run in the browser. empty was exactly what I needed.Fabrizio
F
1

Install vite-plugin-node-polyfills

npm install --save-dev vite-plugin-node-polyfills

or yarn add --dev vite-plugin-node-polyfills

and add the import import { nodePolyfills } from "vite-plugin-node-polyfills";

to vite.config.ts and add nodePolyfills() to nodePolyfills()

Future answered 29/3 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.