How to Resolve Vite CJS Build Warning: Uanderstanding Module Systems
반응형
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
Add ESM Configuration to package.json:
{ "type": "module" }
Change Configuration File Extension:
JavaScript:
vite.config.js
→vite.config.mjs
TypeScript:
vite.config.ts
→vite.config.mts
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:
- Synchronous Loading:
- Blocks HTML parsing
Sequential execution guaranteed
async:
- Asynchronous loading
- Execution order not guaranteed
Suitable for independent scripts
defer:
- Executes after HTML parsing
- Execution order guaranteed
Ideal for dependent scripts
type="module":
- Automatic defer behavior
- Strict mode by default
CORS rules applied
inline:
- Immediate execution
- No caching
- No additional requests
반응형
'OK' 카테고리의 다른 글
React에서 람다 함수를 선호하는 4가지 이유 (화살표 함수 활용법) (0) | 2024.11.01 |
---|---|
Vite CJS 빌드 경고 해결 방법: 모듈 시스템 이해하기 (0) | 2024.10.30 |
Node.js 프로젝트의 폴더 구조 가이드: 단수와 복수 네이밍 컨벤션 (0) | 2024.10.30 |
error: RPC failed; HTTP 400 curl 22 The requested URL returned error: 400 (0) | 2024.10.30 |