与 webpack 捆绑后枚举的"无法读取未定义的属性"



我有一个 React 库,我想使用 Webpack 进行构建。该库是使用 Typescript 编写的。似乎一切正常,但由于某种原因枚举没有。

当我将库安装到我的 React 应用程序中时,我在浏览器控制台中找到了枚举的Cannot read properties of undefined

我尝试查看输出的捆绑包,但枚举似乎正在编译到捆绑包中。我觉得我一定在某个地方配置错误。在我能够捆绑microbundle-crl之前,我们正在从 Webpack 转向 Webpack。

这是我webpack.config.js文件:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const DtsBundleWebpack = require('dts-bundle-webpack');
module.exports = {
mode: 'production',
entry: './src/index.tsx',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
resolve: {
extensions: ['.tsx', '.ts', '.json', 'jsx', '.js'],
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /.(ts|tsx)$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /.css$/,
use: [
MiniCssExtractPlugin.loader, //Extract css into files
'css-loader', // Turns css into commonjs
],
},
{
test: /.pcss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader', // Turns css into commonjs
'postcss-loader'
]
},
],
},
plugins: [
new MiniCssExtractPlugin({ filename: 'randomcompany-components.css' }),
new DtsBundleWebpack({
name: '@randomcompany/components',
main: './dist/src/index.d.ts',
out: '../index.d.ts',
}),
],
};

tsconfig.json如下:

{
"compilerOptions": {
"outDir": "dist",
"module": "esnext",
"lib": ["dom", "esnext"],
"types": ["react", "react-scripts"],
"moduleResolution": "node",
"jsx": "react",
"sourceMap": true,
"declaration": true,
"declarationDir": "dist",
"esModuleInterop": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"isolatedModules": true,
"preserveConstEnums": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true
},
"include": ["src", "src/lang"],
"exclude": ["node_modules", "dist", "src/stories"]
}

我的枚举是这样的格式:

export enum Test {
TestOne = "Test One",
TestTwo = "Test Two",
TestThree = "Test Three"
};
export default Test;

你应该这样写:

const Test = {
TestOne: "Test One",
TestTwo: "Test Two",
TestThree: "Test Three",
};
export default Test;

但在我看来,使用enum会使您的捆绑文件有点重,只是建议。 使用简单的 JavaScript 对象。