繁体   English   中英

使用webpack创建供应商和应用程序捆绑,并使用requirejs加载

[英]with webpack create vendor and app bundles and load with requirejs

是否可以使用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(网络选项卡显示),但返回的app对象未定义。

可以在不使用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]"]
    },

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM