首页 > 解决方案 > 自定义 React 组件库在使用全局的非节点运行环境中不起作用

问题描述

我有一个反应组件库,我尝试使用未在节点环境中运行的应用程序,编译后的版本通过脚本标签包含。

由于它不支持导入,我试图将它分配给窗口。

将编译好的js导入消费者项目时出现以下错误:

global is not defined弹出,窗口不包含Components我分配给窗口的对象。

是否有可能使其适用于节点和 Web 环境?

组件:(index.ts)

import { Button } from "./src/components/Button/Button";
export { default as Button } from './src/components/Button/Button';

window.Components = {
    Button,
};

网页包:

/* eslint-disable import/no-extraneous-dependencies */
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const { merge } = require('webpack-merge')
const { resolve } = require("path");

const TerserPlugin = require('terser-webpack-plugin');
const DtsBundleWebpack = require('dts-bundle-webpack')
const nodeExternals = require('webpack-node-externals');
const commonConfig = require('./webpack.common.config')

module.exports = merge(commonConfig , {
    entry: resolve(__dirname, './', 'index.ts'),
    mode: 'production',
    target: 'node',
    node: {global: true},
    output: {
        filename: '[name].js',
        chunkFilename: '[name].js',
        libraryTarget: 'umd',
        library: 'Components'
    },
    optimization: {
        minimizer: [
            new TerserPlugin({
                parallel: true,
                cache: true,
            }),
        ],
        splitChunks: {
            cacheGroups: {
                vendors: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'initial',
                },
                async: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'async',
                    chunks: 'async',
                    minChunks: 4,
                },
            },
        },
    },
    externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
    plugins: [
        new CleanWebpackPlugin(),
        new DtsBundleWebpack({
            name: "components",
            main: resolve(__dirname, './', 'index.d.ts'),
            out:  resolve(__dirname, './', 'dist/main.d.ts'),
        })
    ],
});

标签: javascriptreactjswebpack

解决方案


推荐阅读