개발
How to Resolve Vite CJS Build Warning: Uanderstanding Module Systems
syaku
2024. 10. 30. 14:40
반응형
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
반응형