Javascript 如何从网页包构建的*外部*同步要求网页包构建模块
假设我有这样一个HTML文件:Javascript 如何从网页包构建的*外部*同步要求网页包构建模块,javascript,html,webpack,webpack-2,Javascript,Html,Webpack,Webpack 2,假设我有这样一个HTML文件: <!DOCTYPE html> <meta charset="UTF-8"> <title>Suman tests</title> <head> <script src="../dist/suman.js"></script> <-- webpack build here // how can I do a synchronous r
<!DOCTYPE html>
<meta charset="UTF-8">
<title>Suman tests</title>
<head>
<script src="../dist/suman.js"></script> <-- webpack build here
// how can I do a synchronous require() here, from something
// inside the Webpack build?
</script>
</head>
<body>
</body>
</html>
苏曼测验
我想我对这个问题有一个答案,其实很聪明。解决方案使用Webpack
在使用Webpack构建之前,在我们的后端代码中,我们将执行以下操作:
global.require = name => { // global is window
switch (name) {
case 'async':
return require('async');
case 'bluebird':
return require('bluebird')
case 'socket.io':
return require('socket.io')
// etc etc
}
}
我们需要使用完整/实际路径,而不是动态路径,这样Webpack就可以完成它的任务
网页包将包含此代码作为构建的一部分,并从中删除F。但这并不重要,因为在捆绑包之外,我们将有一种方法需要Webpack模块
<script src="../dist/suman.js"></script> <-- webpack build here
<script>
// this will pull async from inside the Webpack build
const async = window.require('async');
const socketio = window.require('socket.io');
const Promise = window.require('bluebird');
</script>
您是指如何延迟加载模块吗?因为webpack在浏览器运行任何代码之前捆绑了所有的需求。@Omriuzon我是否可以延迟加载。但我之所以使用synchronous这个词是因为:)“synchronous”的意思是“不延迟加载”。如果它已经在Webpack构建中,那么它已经在那里同步加载了…理论上。如果在浏览器可以运行之前,所有的代码都捆绑在一起,那么同步和异步模块加载是没有意义的。不是真的,你可以加载代码,然后异步加载更多的代码。我个人喜欢异步/延迟加载,但在本例中,我希望只执行严格的同步require()调用。因此,您的意思是代码已经在捆绑包中,因此不需要它,这是默认行为。
<script src="../dist/suman.js"></script> <-- webpack build here
<script>
// this will pull async from inside the Webpack build
const async = window.require('async');
const socketio = window.require('socket.io');
const Promise = window.require('bluebird');
</script>