我正在开发一个库,希望它同时适用于节点和浏览器。
假设我有这个库文件mylibrary.js:
module.exports = {
add: function (a, b) {return a + b;},
sub: function (a, b) {return a - b;}
};
Run Code Online (Sandbox Code Playgroud)
我可以在节点应用程序中很好地使用它,如下所示fun.js:
const mylibrary = require('mylibrary'); // CommonJS style
import {add, sub} from 'mylibrary'; // UMD style
var x = mylibrary.add(1, 2); // method 1
var y = add(1, 2); // method 2
Run Code Online (Sandbox Code Playgroud)
这两种方法都可以正常工作,没有问题。
现在我希望能够通过以下方式在浏览器中使用它:
<script src="mylibrary.min.js"></script>
<script>
var x = add(1, 2); // doesn't work! Using mylibrary.add() will work
var y = sub(1, 2); // but I want to use sub() directly; not mylibrary.sub()
</script>
Run Code Online (Sandbox Code Playgroud)
我想直接在浏览器中公开add()和sub()直接在浏览器中公开,而不需要用户用任何名称对其进行限定(我知道通常建议将库中的所有函数组合在一个通用名称下以避免名称空间冲突;但在我的情况下这是可以的) .
目前我使用下列webpack.config.js但它暴露add()并sub()称为对象下mylibrary。因此,在浏览器中,用户必须编写mylibrary.add()我想避免的内容。
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './lib/mylibrary.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'mylibrary.min.js',
libraryTarget: 'umd',
library: 'mylibrary' // need to avoid this for the browser
}
};
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
在 webpack配置页面之后,使用此配置:
const path = require('path');
module.exports = {
entry: './lib/mylibrary.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'mylibrary.min.js',
libraryTarget: 'window'
}
};
Run Code Online (Sandbox Code Playgroud)
所以 libraryTarget 是 'window' 和 library in undefined
| 归档时间: |
|
| 查看次数: |
3492 次 |
| 最近记录: |