webpack-library(库文件打包)

开发一个库文件,实现加减功能

项目目录如下


项目目录

webpack.config.js 代码

const path = require('path');
module.exports = {
    entry: {
        index: './src/index.js'
    },
    output: {
        filename: '[name].js',
        path:  path.resolve(__dirname, 'build')
    }
}

math-sub.js 代码

export default function(a, b) {
    return a + b;
}

math-add.js 代码

export default function(a, b) {
    return a + b;
}

index.js 代码

import * as add from './math-add';
import * as sub from './math-sub';

export default {
    add, 
    sub
}

命令行运行 webpack --config webpack.config.js 执行打包,可以打包成功
但是你打包的library文件里面定义的两个方法外部无法获取并使用

打包的文件,使用的方法通常有四种

  • es6
    import library from './libray'
  • cmd
    const library = require('./library')
  • amd
    define(['./library'], function(_library) { console.log(_library) })
  • script标签引入

为了符合使用需求

webpack.config.js 改造,在output上添加两个配置属性

const path = require('path');

module.exports = {
    entry: {
        index: './src/index.js'
    },
    output: {
        filename: '[name].js',
        path:  path.resolve(__dirname, 'build'),
        // 在window上挂载属性library
        library: 'library',
        /*
         umd 通用配置,这样可以通过 es6 amd cmd 方式使用库
         libraryTarget 属性有多中配置,具体可以看webpack官网 指南 -> 创建library
        */
        libraryTarget: 'this',
    }
}

这样打包出来的代码,可以通过上面四种方式使用

你可能感兴趣的:(webpack-library(库文件打包))