> Hello World !!!

     

@syaku

How to Resolve Vite CJS Build Warning: Uanderstanding Module Systems

728x90
반응형

Complete Guide to Vite Module System: From CJS Warning Resolution to ESM Migration

Resolving Vite's CJS Build Warning

In Vite 5, you might encounter this warning:

The CJS build of Vite's Node API is deprecated. See https://vite.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.

Solutions

  1. Add ESM Configuration to package.json:

    {
    "type": "module"
    }
    
  2. Change Configuration File Extension:

  3. JavaScript: vite.config.jsvite.config.mjs

  4. TypeScript: vite.config.tsvite.config.mts

  5. Modify Import Aliases:

// Before (CJS style)
alias: {
  '@': path.resolve(__dirname, './src')
}

// After (ESM style)
import { fileURLToPath } from 'url'
import { dirname, resolve } from 'path'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

export default {
  resolve: {
    alias: {
      '@': resolve(__dirname, './src')
    }
  }
}

JavaScript Module Systems

1. CJS (CommonJS)

// Exporting
module.exports = { myFunction };

// Importing
const { myFunction } = require('./module');

Characteristics:

  • Node.js default module system
  • Synchronous loading
  • Runtime module resolution

2. ESM (ES Modules)

// Exporting
export const myFunction = () => {};

// Importing
import { myFunction } from './module';

Characteristics:

  • Modern JavaScript standard
  • Static analysis capability
  • Tree-shaking support

3. UMD (Universal Module Definition)

(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['dependency'], factory);
    } else if (typeof module === 'object' && module.exports) {
        module.exports = factory(require('dependency'));
    } else {
        root.myModule = factory(root.dependency);
    }
}(this, function(dependency) {
    return {};
}));

HTML Script Loading Methods

<!-- 1. Synchronous Loading -->
<script src="script.js"></script>

<!-- 2. Asynchronous Loading -->
<script async src="script.js"></script>

<!-- 3. Deferred Loading -->
<script defer src="script.js"></script>

<!-- 4. ES Module -->
<script type="module" src="script.js"></script>

<!-- 5. Inline Script -->
<script>
  console.log('Immediate execution');
</script>

Characteristics of Each Method:

  1. Synchronous Loading:
  2. Blocks HTML parsing
  3. Sequential execution guaranteed

  4. async:

  5. Asynchronous loading
  6. Execution order not guaranteed
  7. Suitable for independent scripts

  8. defer:

  9. Executes after HTML parsing
  10. Execution order guaranteed
  11. Ideal for dependent scripts

  12. type="module":

  13. Automatic defer behavior
  14. Strict mode by default
  15. CORS rules applied

  16. inline:

  17. Immediate execution
  18. No caching
  19. No additional requests
728x90
반응형