- ES2015模块导入:
import * as webpackNumbers from 'webpack-numbers';
// ...
webpackNumbers.wordToNum('Two');
- CommonJS模块需要:
var webpackNumbers = require('webpack-numbers');
// ...
webpackNumbers.wordToNum('Two');
- AMD模块要求:
require(['webpackNumbers'], function ( webpackNumbers) {
// ...
webpackNumbers.wordToNum('Two');
});
- 通过脚本标签加载库:
<!doctype html>
<html>
...
<script src="https://unpkg.com/webpack-numbers"></script>
<script>
// ...
// Global variable
webpackNumbers.wordToNum('Five')
// Property in the window object
window.webpackNumbers.wordToNum('Five')
// ...
</script>
</html>
例外处理:
import _ from 'lodash';
import numRef from './ref.json';
export function numToWord(num) {
return _.reduce(numRef, (accum, ref) => {
return ref.num === num ? ref.word : accum;
}, '');
}
export function wordToNum(word) {
return _.reduce(numRef, (accum, ref) => {
return ref.word === word && word.toLowerCase() ? ref.num : accum;
}, -1);
}
[
{
"num": 1,
"word": "One"
},
{
"num": 2,
"word": "Two"
},
{
"num": 3,
"word": "Three"
},
{
"num": 4,
"word": "Four"
},
{
"num": 5,
"word": "Five"
},
{
"num": 0,
"word": "Zero"
}
]
var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'webpack-numbers.js'
},
+ externals: {
+ lodash: {
+ commonjs: 'lodash',
+ commonjs2: 'lodash',
+ amd: 'lodash',
+ root: '_'
+ }
+ }
// externals: {
// react: 'React',
// 'react-dom': 'ReactDOM',
// 'react-router': 'ReactRouter',
// lodash: '_',
// d3: 'd3',
// echarts: 'echarts',
// moment: 'moment',
// },
};
// webpack.config.js
var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'webpack-numbers.js',
+ library: 'webpackNumbers',
+ libraryTarget: 'umd'
},
externals: {
lodash: {
commonjs: 'lodash',
commonjs2: 'lodash',
amd: 'lodash',
root: '_'
}
}
};
您可以通过以下方式公开库:
- 变量:作为
script
tag(libraryTarget:'var'
)提供的全局变量。 - 这个:通过
this
object(libraryTarget:'this'
)获得。 - 窗口:
window
在浏览器(libraryTarget:'window'
)中通过对象可用。 - UMD:在AMD或CommonJS
require
(libraryTarget:'umd'
)之后可用。
如果library
已设置libraryTarget
且未设置,则libraryTarget
默认var
为输出配置文档中指定的值。见output.libraryTarget那里的所有可用选项的详细列表。
output.libraryTarget
一共支持的值:
- var - 默认值
- assign
- this
- window
- global
- commonjs
- commonjs2
- amd
- umd
- jsonp