首页 > 解决方案 > 将 React 组件拆分为小部件

问题描述

我正在尝试从我现有的反应应用程序创建 JS 小部件。所以目前我有一个看起来像这样的应用程序

-src 
  - config
  - components
  - containers
  - lib
  - assets
  - widgets
    - widgetOne
    - widgetTwo
      - components
      - widget.js
      - index.js
  - index.js
  - index.html

因此,我希望小部件目录中的目录是自包含的应用程序,我可以将其分解为单独的 js 文件,并且客户端可以将 js 脚本添加到其页面中的脚本标记中。

我已经接近但仍然面临一些问题。另外,我想看看是否有人有按照更好的模式执行此操作的经验。

现在我正在使用 webpack 进行拆分。我只是定义/src/widgets/widgetOne/index.js为一个入口点并完美地创建了一个单独的文件。

这是我的网络包:

const appConstants = function() {
    switch (process.env.NODE_ENV) {
        case 'local':
            const localConfig = require('./config/local');
            return localConfig.config();
        case 'development':
            const devConfig = require('./config/development');
            return devConfig.config();
        case 'production':
        default:
            const prodConfig = require('./config/production');
            return prodConfig.config();
    }
};

const HtmlWebPackPlugin = require("html-webpack-plugin");
const webpack = require('webpack');

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const htmlWebpackPlugin = new HtmlWebPackPlugin({
    template: "./src/index.html",
    filename: "./index.html",
    hash: true
});

let webpackConfig = {
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.css$/,
                exclude: [ /assets/, /node_modules/ ],
                use: [
                    {
                        loader: "style-loader"
                    },
                    {
                        loader: "css-loader",
                        options: {
                            modules: true,
                            importLoaders: 1,
                            localIdentName: "[name]_[local]_[hash:base64]",
                            sourceMap: true,
                            minimize: true
                        }
                    }
                ]
            },
            {
                test: /\.(pdf|jpg|png|gif|svg|ico)$/,
                exclude: [/node_modules/],
                use: [
                    {
                        loader: 'file-loader'
                    },
                ]
            },
            {
                test: /\.(woff|woff2|eot|ttf|svg)$/,
                exclude: [/node_modules/],
                use: {
                    loader: 'url-loader?limit100000'
                }
            }
        ]
    },
    entry: {
        main: [ "@babel/polyfill", "./src/index.js"],
        widgetOne: ["./src/widgets/widgetOne/index.js"]
    },
    output: {
        publicPath: appConstants().BASENAME ? JSON.parse(appConstants().BASENAME) : '/'
    }, 
    optimization: {
        splitChunks: {
            chunks: 'all'
        }
    },
    plugins: [
        htmlWebpackPlugin,
        new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /en/),
        new BundleAnalyzerPlugin({
            analyzerMode: 'disabled',
            generateStatsFile: true,
            statsOptions: { source: false }
        }),
        new webpack.DefinePlugin({
            'process.env': appConstants()
        }),
        new webpack.EnvironmentPlugin(['NODE_ENV'])
    ],
    devServer: {
        historyApiFallback: true,
        port: 9090
    }
};

module.exports = webpackConfig;

我现在遇到的问题是widgetOne.js
1) 我最终得到了一个 vendor~widgetOne.js 文件,我还需要包含该文件才能使 widgetOne 应用程序正常工作。
2)我不想要的主应用程序widgetOne.js也被添加到我的文件中。index.html

有没有办法正确配置 webpack 以使其工作?

标签: javascriptreactjswebpack-4

解决方案


所以,这是我想出的似乎可行的解决方案。我仍然不知道这是否是最好的方法,但这是我唯一能够为我工作的方法。

我决定将小部件构建为不同的环境过程,并根据该环境修改 webpack 配置。

所以 package.json 我在脚本下添加了这一行:
"build-widgets": "cross-env NODE_ENV=plugins webpack --mode development",

我将此部分添加到webpack.config.js文件的末尾:

// Override webpack configs when building plugins
if ( process.env.NODE_ENV === 'plugins') {
    webpackConfig.entry = {
       widgetOne: [ "@babel/polyfill", "./src/plugins/widgetOne/index.js"]
    }
    webpackConfig.output = {
    publicPath: appConstants().DS_BASENAME ? JSON.parse(appConstants().DS_BASENAME) : '/',
        path: __dirname + '/dist/widgets',
        library: 'MyApp',
        libraryTarget: 'umd',
        umdNamedDefine: true
   }
}

或者,我可以只添加第二个webpack.config.js专门来处理我的小部件构建。在我的情况下,我还没有觉得需要它,但这是肯定要考虑的,只是为了保持配置分开。


推荐阅读