看rollup文档的时候发现上面有提到从cdn加载依赖,需要配置ouput.paths,设置后确实发现依赖的代码文件地址注入到了打包出来的文件,不过这个文件不管是在node环境还是在浏览器,都跑不起来,具体是怎么使用的呢?
rollup.config.js
配置如下:(amd
格式)
import resolve from 'rollup-plugin-node-resolve';
export default {
input: 'src/main.js',
output: {
file: 'bundle.js',
name: 'X',
format: 'amd',
globals: {
lodash: '_',
jquery: 'jQuery'
},
paths: {
jquery: 'https://cdn.bootcss.com/jquery/3.2.1/jquery.js'
},
},
// 指出应将哪些模块视为外部模块
external: ['lodash', 'jquery'],
plugins: [resolve({})],
};
打包出来的文件如下:
define(['lodash', 'https://cdn.bootcss.com/jquery/3.2.1/jquery.js'], function (_, $) { 'use strict';
_ = _ && _.hasOwnProperty('default') ? _['default'] : _;
$ = $ && $.hasOwnProperty('default') ? $['default'] : $;
var index = 42;
function main () {
console.log('the answer is ' + index);
console.info(_.join(['a', 'b', 'c'], '~'));
}
$('#p').html('rollup打包,将jquery当成外部引入模块');
return main;
});
浏览器和node下运行结果:
umd
格式
import resolve from 'rollup-plugin-node-resolve';
export default {
input: 'src/main.js',
output: {
file: 'bundle.js',
name: 'X',
format: 'umd',
globals: {
lodash: '_',
jquery: 'jQuery'
},
paths: {
jquery: 'https://cdn.bootcss.com/jquery/3.2.1/jquery.js'
},
},
// 指出应将哪些模块视为外部模块
external: ['lodash', 'jquery'],
plugins: [resolve({})],
};
打包后结果:
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('lodash'), require('https://cdn.bootcss.com/jquery/3.2.1/jquery.js')) :
typeof define === 'function' && define.amd ? define(['lodash', 'https://cdn.bootcss.com/jquery/3.2.1/jquery.js'], factory) :
(global = global || self, global.X = factory(global._, global.jQuery));
}(this, function (_, $) { 'use strict';
_ = _ && _.hasOwnProperty('default') ? _['default'] : _;
$ = $ && $.hasOwnProperty('default') ? $['default'] : $;
var index = 42;
function main () {
console.log('the answer is ' + index);
console.info(_.join(['a', 'b', 'c'], '~'));
}
$('#p').html('rollup打包,将jquery当成外部引入模块');
return main;
}));
浏览器运行结果:
在手动引入jquery后运行正确
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p id="p"></p>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
<script src="./bundle.js"></script>
<script>
console.info(X());
</script>
</body>
</html>
那如果是这样的话这个paths到底是有什么用的?