将 React 组件拆分为小部件

3

我正在尝试从现有的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作为入口点,并完美地创建了一个单独的文件。

这是我的webpack:

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 的方法来解决这个问题?

1个回答

0

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

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

因此,在package.json中,我在scritps下添加了以下行:
"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文件来专门处理我的小部件构建。在我的情况下,我还没有感到需要,但这是值得考虑的,只是为了保持配置分离。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接