如何配置Webpack-Borrower中的libraryTarget + splitChunks + requaire

时间:2019-05-27 22:25:55

标签: webpack import requirejs require

我正在用JS编写网页的库,然后由Webpack对其进行“编译”。我需要在单独的Webpack项目中的页面上导入/重新存储库(如requirejs)。 Lib可以托管在两个单独的路径上-一个是相对的,第二个是绝对的。我该如何配置webpack来导出可以在另一个项目中导入/需要的库?

我尝试了umd,amd,window,this等。在所有情况下,对require的响应都是不确定的或抛出错误。

我的libs webpack配置:

const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

let glob = require('glob'),
    entryObject = glob.sync('./src/js/*.js').reduce(
        function (entries, entry) {
            let matchForRename = /^\.\/src\/(.+)\.js$/g.exec(entry);

            if (matchForRename !== null && typeof matchForRename[1] !== 'undefined') {
                let entryName = matchForRename[1];

                if (typeof entries[entryName] !== 'undefined') {
                    entries[entryName].push(entry);
                } else {
                    entries[entryName] = [entry];
                }

            }

            return entries;
        }, {}
    );

module.exports = env => {
    return {
        devtool: env.production === 'true' ? false : 'eval-source-map',
        target: 'web',
        entry: entryObject,
        output: {
            chunkFilename: '[name].js',
            publicPath: 'dist/',
            libraryTarget: 'umd',
        },
        optimization: {
            splitChunks: {
                chunks: 'all',
                maxInitialRequests: Infinity,
                minSize: 0,
                cacheGroups: {
                    vendor: {
                        test: /[\\/]node_modules[\\/]/,
                        name(module) {
                            // get the name. E.g. node_modules/packageName/not/this/part.js
                            // or node_modules/packageName
                            const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

                            // npm package names are URL-safe, but some servers don't like @ symbols
                            return `js/npm/${packageName.replace('@', '')}`;
                        },
                    }
                },
            }
        },
        module: {
            rules: [{
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                },
            }, ]
        },
        plugins: [
            new CleanWebpackPlugin(),
            new CopyWebpackPlugin([{
                from: 'src/php',
                to: 'php'
            }], {
                copyUnmodified: true
            })
        ]
    }
};

在网页项目中,我尝试了以下操作(使用requirejs):

window.require.config({
    baseUrl: '../../libs/',
    paths: {
        prod: 'http://example.com/libs/'
    }
});

window.require(['js/main'], function (main) {
        console.log(main);
    },
    function (err) {
        window.require(['prod/js/main'],
            function (main) {
                console.log(main);
            });
    }
);

或仅通过webpack:

import('../../libs/js/main.js').then(function (main) {
            console.log('ok');
        })
        .catch(function (error) {});
    try {
        require(['../../libs/js/main.js'], function (main) {
            console.log(main);
        }, function (error) {});
    } catch (error) {}
    try {
        define('../../libs/js/main.js', [], function () {
            console.log('ok');
        }, function (error) {
            console.log('error');
        });
    } catch (error) {}
    try {
        define(['../../libs/js/main.js'], function () {
            console.log('ok');
        }, function (error) {
            console.log('error');
        });
    } catch (error) {}
    try {
        define('main', ['../../libs/js/main.js'], function () {
            console.log('ok');
        }, function (error) {
            console.log('error');
        });
    } catch (error) {}

如果我在libs webpack conf中不使用优化选项,则requirejs可以正常工作,但是如果使用优化requirejs,请重新运行undefined:/。

0 个答案:

没有答案