如何使用Webpack 4公开javascript模块的默认导出对象?

问题描述 投票:1回答:1

我有一个javascript es6模块导出一个对象,如下所示:

import HealthCarePlan from './health_care_plan/health-care-plan';
import CourseRequest from './course_request/course-request';

export default {
    CourseRequest: CourseRequest,
    HealthCarePlan: HealthCarePlan
};

如何告诉webpack将该对象导出到名为appScripts的全局变量?我希望能够从全球范围中引用appScripts.CourseRequestappScripts.HealthCarePlan

这是我当前的webpack(拆分为common,dev.babel和dev.include模块):

index.js

export default {
    one: 'one',
    two: 'two'
}

webpack.common.babel.js

import path from 'path';
import webpack from 'webpack';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import webpackRxjsExternals from 'webpack-rxjs-externals';

const appsPath = 'powerschool_apps';
const staticPath = `${appsPath}/static`;

const config = {
    target: 'web',
    node: {
        fs: 'empty'
    },
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'static/bundles'),
        publicPath: 'http://localhost:8081/',
        library: 'app',
        libraryTarget: 'var'
    },
    entry: {
        app: [
            './powerschool_apps/static/js/index.js'
        ],
        vendor: [
            'jquery',
            `./${staticPath}/js/vendor-include.js`,
            `./${staticPath}/lib/materialize/js/bin/materialize.js`,
            'iframe-resizer',
            'underscore',
            `./${staticPath}/lib/materialize/sass/materialize.scss`,
        ]
    },
    performance: {
        hints: false
    },
    optimization: {
        splitChunks: {
            cacheGroups: {
                default: false,
                commons: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendor_app',
                    chunks: 'all',
                    minChunks: 2
                }
            }
        }
    },
    externals: [
        webpackRxjsExternals()
    ],
    module: {
        rules: [
            {
                test: /\.(ttf|eot|woff|woff2)/,
                loader: 'file-loader',
                options: {
                    name: 'fonts/[name].[ext]',
                }
            },
            {
                test: /\.(png|svg|gif)$/,
                loader:
                    'file-loader',
                options: {
                    name: 'images/[name].[ext]',
                },
            },
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader'
                ]
            },
        ]
    },
    plugins: [
        // new HardSourceWebpackPlugin(),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
        }),
    ],
    resolve: {
        modules: [
            '/node_modules'
        ]
    }
};

export default config;

webpack.dev.babel.js

require('babel-register');
import path from 'path';
import webpack from 'webpack';
import merge from 'webpack-merge';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';

import common from './webpack.common.babel';

export default merge(common, {
    devtool: 'inline-source-map',
    mode: 'development',
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: [
                    'css-hot-loader',
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'sass-loader'
                ]
            },
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name].bundle.css',
            chunkFilename: '[id].css'
        }),
        new webpack.NamedModulesPlugin()
    ],
    serve: {
        dev: {
            headers: {
                'Access-Control-Allow-Origin': '*'
            }
        },
        host: '0.0.0.0',
        port: '8081',
        clipboard: false,
        hot: {
            port: '8500',
            host: {
                client: 'localhost',
                server: '0.0.0.0'
            }
        }
    }
});

webpack.dev.include.js

require('babel-register');

const config = require('./webpack.dev.babel');

module.exports = config.default;

webpack.prod.babel.js

import path from 'path';
import merge from 'webpack-merge';
import CleanWebpackPlugin from 'clean-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import BundleTracker from 'webpack-bundle-tracker';

import common from './webpack.common.babel';

export default merge(common, {
    mode: 'production',
    output: {
        filename: '[name].[hash].js',
        path: path.resolve(__dirname, 'static/bundles'),
        publicPath: 'http://localhost:8081/static/bundles/'
    },
    module: {
        rules: [{
            test: /\.(css|scss|sass)$/,
            use: [
                MiniCssExtractPlugin.loader,
                'css-loader',
                'sass-loader'
            ]
        }],
    },
    plugins: [
        new CleanWebpackPlugin(['./powerschool_apps/static/bundles/*']),
        new BundleTracker({
            filename: './webpack-stats.json'
        }),
        new MiniCssExtractPlugin({
            // Options similar to the same options in webpackOptions.output
            // both options are optional
            filename: '[name].[hash].css',
            chunkFilename: '[id].css'
        }),
    ]
})

package.json依赖项

"dependencies": {
  "@reactivex/rxjs": "^6.0.0",
  "bootstrap": "^4.0.0",
  "bootstrap-markdown": "^2.10.0",
  "font-awesome": "^4.7.0",
  "font-awesome-animation": "^0.2.0",
  "gulp": "gulpjs/gulp.git#4.0",
  "hammerjs": "^2.0.8",
  "iframe-resizer": "^3.5.16",
  "jquery": "^3.3.1",
  "jquery-datetimepicker": "^2.5.16",
  "jquery.formset": "^1.3.0",
  "ladda": "^1.0.5",
  "materialize-autocomplete": "^1.0.7",
  "rx-dom": "^7.0.3",
  "select2": "^4.0.6-rc.1",
  "underscore": "^1.8.3"
},
"devDependencies": {
  "babel-core": "^6.26.0",
  "babel-loader": "^7.1.2",
  "babel-preset-env": "^1.6.1",
  "babel-preset-es2015": "^6.24.1",
  "babel-preset-stage-0": "^6.24.1",
  "browser-sync": "^2.23.7",
  "clean-webpack-plugin": "^0.1.19",
  "css-hot-loader": "^1.3.9",
  "css-loader": "^0.28.11",
  "file-loader": "^1.1.11",
  "merge-stream": "^1.0.1",
  "mini-css-extract-plugin": "^0.4.0",
  "normalize-package-data": "^2.4.0",
  "run-sequence": "^2.2.1",
  "sass-loader": "^7.0.1",
  "source-map-loader": "^0.2.3",
  "style-loader": "^0.21.0",
  "webpack": "^4.6.0",
  "webpack-bundle-tracker": "^0.3.0",
  "webpack-cli": "^2.0.15",
  "webpack-hot-client": "^2.2.2",
  "webpack-merge": "^4.1.2",
  "webpack-rxjs-externals": "^2.0.0",
  "webpack-stream": "^4.0.0"
},

我开始使用webpack-servewebpack-serve --config webpack.dev.include.js。在Chrome DevTools中,当我打开控制台并输入app并点击enter时,我得到了undefined

但是,当我运行webpack --config webpack.prod.babel.js并在DevTools控制台中键入app时,我回到了{one: 'one', two: 'two'}对象。

我的目标是在Django项目中使用此包。我需要将数据从Django上下文传递到JS函数,这就是我需要将bundle作为库公开的原因。

javascript webpack
1个回答
1
投票

您可以使用ProvidePlugin来执行此操作。首先,您需要为要成为全局的文件创建别名

resolve: {
  alias: {
    appScripts: '/path-to-app-scripts-file'
  }
}

并添加ProvidePlugin

new webpack.ProvidePlugin({
  appScripts: ['appScripts', 'default']
})

现在,无论何时使用全局appScripts变量,它都使用来自appScripts模块的默认导出,该模块是别名到指定文件的。

© www.soinside.com 2019 - 2024. All rights reserved.