是否可以使用webpack创建多个捆绑包(“供应商”,“应用”)并使用requirejs加载它们?在此示例中,我可以创建捆绑包,但是当我尝试使用requirejs加载捆绑包时,返回的模块未定义。
webpack.config.js:
module.exports = {
entry: {
app: './app.js',
//vendor: ['bootstrap', 'popper.js','jquery','underscore']
},
devtool: 'source-map',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js',
libraryTarget: 'umd',
globalObject: 'this',
umdNamedDefine: true,
pathinfo: true
},
resolve: {
alias: {
popper: "popper.js",
},
extensions: ['.js'] // File types
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
]
},
plugins: [
],
optimization: {
namedModules: true,
splitChunks: {
chunks: "async",
cacheGroups: {
app: {
reuseExistingChunk: true,
},
vendor: {
test: /node_modules/,
chunks: 'all',
name: 'vendor',
},
}
},
},
};
index.js
requirejs.config({
paths: {
'vendor': './dist/vendor.bundle',
requireLib: 'require',
'all_app': './dist/app.bundle'
},
bundles: {
'all_app': ['app','./menuTooltips','./NavMenu'],
'vendor': [/*'bootstrap',*/ 'jquery' /*, 'underscore',*/ /*, 'popper'*/ ],
},
nodeIdCompat: true,
});
define(['require', './app'], function (require, app) {
console.log(app); // app is undefined!!!!
app.Init();
});
index.html
<script type="text/javascript" src="./lib/require.min.js" data-main="index.js"></script>
当index.js需要'app'时,将加载dist / app.bundle(网络标签显示),但返回的应用程序对象未定义。
答案 0 :(得分:0)
可以在不使用requirejs的情况下加载应用捆绑包(必须首先包括供应商捆绑包):
index.html
<script type="text/javascript" src="./dist/vendor.bundle.js"></script>
<script type="text/javascript" src="./dist/app.bundle.js"></script>
<script>
window.onload = function () {
MyLib.app.Init();
};
</script>
webpack.config.js
添加了“库”行:
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js',
libraryTarget: 'umd',
globalObject: 'this',
umdNamedDefine: true,
library: ["MyLib", "[name]"]
},