【webpack】中library的作用

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>
复制代码
posted @ 2020-07-24 08:56  h2z  阅读(567)  评论(0编辑  收藏  举报