// ./src/index.js
export const add = (x, y) => {
return x + y
}
// webpack.config.js
const path = require('path')
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'build.js',
path: path.resolve(__dirname, './dist'),
library: 'libs'
//library: [
// name: 'libs',
// type: 'window'
//]
}
}
webpack 打包好之后,我们就可以在其它html文件的script标签引入打包好的那个文件了
// ./demo/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="../dist/build.js"></script>
<script>
console.log(libs.add(1, 1)); // 2
</script>
</body>
</html>
上述方法只能使打出来的包用在html的script标签,那么我们如何让它兼容不同的环境呢?
commonjs 环境
// webpack.config.js
const path = require('path')
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'build.js',
path: path.resolve(__dirname, './dist'),
library: [
name: 'libs',
type: 'commonjs'
]
}
}
// ./demo/index.js
const { libs } = require('../dist/build.js')
console.log( libs.add(2, 3))
esModule 环境
// webpack.config.js
const path = require('path')
module.exports = {
mode: 'production',
entry: './src/index.js',
// 此配置为实验性配置
experiments: {
outputModule: true
},
output: {
filename: 'build.js',
path: path.resolve(__dirname, './dist'),
library: [
type: 'module'
]
}
}
// ./demo/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module">
import { add } from '../dist/build.js'
console.log(add(2, 2)) // 4
</script>
</body>
</html>
上述方法中,我们是分别设置了对应环境的打包配置,那么能不能设置一个值支持所有环境呢?
type: ‘umd’ 支持script 标签、AMD、commonjs
// webpack.config.js
const path = require('path')
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'build.js',
path: path.resolve(__dirname, './dist'),
library: [
name: 'libs',
type: 'umd'
],
globalObject: 'globalThis'
}
}
// ./demo/index.js
const { add } = require('../dist/build.js')
console.log( add(2, 3)) // 5