webpack默認打包之后的代碼形式是這樣的(假設我導出 module.exports = 'hello world' )
(function () { return 'hello world' })()
注意:代碼是一個自執行函數,外界想獲取函數里面的返回值怎么辦(也就是模塊的導出結果 hello world ),那么就需要配置一個 library
const path = require('path') module.exports = { entry: './src/utils.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', library: 'result' } }
然后打包之后是這樣的形式
var result = (function () { return 'hello world' })()
通過把導出的結果賦值給 result 變量,配置了 library: 'result'
將打包之后的文件引入到HTML文件中,可以直接使用哦!(假設打包的文件名是bundle.js)
<body>
<script src="./dist/bundle.js"></script>
<script>
console.log(result)
</script>
</body>
如果你不想在HTML中使用,想在一個JS文件里面通過 require 導入來使用,需要這么配置
const path = require('path') module.exports = { entry: './src/utils.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', libraryTarget: 'commonjs2' } }
打包之后代碼是這樣的
module.exports = (function () { return 'hello world' })()
可以在JS文件中導入來使用
import result from './bundle'
console.log(result)
同時支持import和require語法引入
兩個配置同時使用,生效的是第二種模式。