webpack 支持 ESModel 规范和 CommonJS 规范
一、ESModel 规范
ESModel 模块导入方式:import
ESModel 模块导出方式:export、export default
1. export 导出 和 import {}、import * as 导入
javascript
export const name = 'alias'
export const age = () => {
return 18
}
xml
<template>
<div id="app">
</div>
</template>
<script>
import { name, age } from './utils/user'
import * as user from './utils/user'
export default {
name: 'App',
created() {
console.log(name) // alias
console.log(age()) // 18
console.log(user.name) // alias
console.log(user.age()) // 18
},
}
</script>
2. export default 导出 和 import 导入
javascript
const name = 'alias'
const age = () => {
return 18
}
export default { name, age }
xml
<template>
<div id="app">
</div>
</template>
<script>
import user from './utils/user'
export default {
name: 'App',
created() {
console.log(user.name) // alias
console.log(user.age()) // 18
},
}
</script>
二、CommonJS 规范
CommonJS 模块导入方式:require
CommonJS 模块导出方式:exports、module.exports
1. exports. 导出 和 require 导入
ini
const name = 'alias'
const age = () => {
return 18
}
exports.name = name
exports.age = age
xml
<template>
<div id="app">
</div>
</template>
<script>
const user = require('./utils/user')
export default {
name: 'App',
created() {
console.log(user.name) // alias
console.log(user.age()) // 18
},
}
</script>
2. module.exports = {} 导出 和 require 导入
ini
const name = 'alias'
const age = () => {
return 18
}
module.exports = {
name,
age,
}
xml
<template>
<div id="app">
</div>
</template>
<script>
const user = require('./utils/user')
export default {
name: 'App',
created() {
console.log(user.name) // alias
console.log(user.age()) // 18
},
}
</script>