使用 React-file-viewer

IT技术 reactjs
2021-05-23 14:36:51

我正在尝试使用 React-file-viewer。Npm 教程在这里但是我在控制台中有一个错误:“你可能需要一个合适的加载器来处理这种文件类型” 这是我的代码:

import FileViewer from 'react-file-viewer';
import { CustomErrorComponent } from 'custom-error';
const file = 'http://example.com/image.png'
const type = 'png'


 onError = (e) => {
    logger.logError(e, 'error in file-viewer');
 }

 <FileViewer
 fileType={type}
 filePath={file}
 errorComponent={CustomErrorComponent}
 onError={this.onError}/>

我指定,我有 babel-preset-es2015 并且我使用它

我能怎么做 ?谢谢

4个回答
module: {
        loaders: [
            // .ts(x) files should first pass through the Typescript loader, and then through babel
            { test: /\.tsx?$/, loaders: ['babel', 'ts-loader'] },
            { test: /\.css$/, loaders: ['style', 'css-loader'] },
            { test: /\.scss$/, loaders: ['style', 'css-loader?modules&importLoaders=1&localIdentName=[local]-[hash:base64:5]', 'postcss-loader', 'sass'] },
            { test: /\.(png|svg|gif|jpg|jpeg)$/, loaders: [ 'url-loader', 'image-webpack?bypassOnDebug'] },
            { test: /\.(eot|woff|ttf|woff2)$/, loader: "file?name=[name].[ext]" }


        ]
    }

你必须在 webpack 配置中包含 babel 作为

loaders: [
      {test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
      { test: /\.jsx$/, exclude: /node_modules/, loader: 'babel-loader' }]

当您使用

onError = (e) => {
    logger.logError(e, 'error in file-viewer');
 }

这是 es6 语法。要使其与浏览器兼容,您必须添加

{test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']}

确保您已安装以下预设和插件,如node-modules/react-file-viewer/.babelrc文件中所列

{
  "presets": [
    "react",
    "es2015",
    "stage-0"
  ],
  "plugins": [
    "transform-class-properties",
    "transform-es2015-classes",
    "transform-es2015-object-super",
    "transform-runtime"
  ]
}

假设您的项目中已经有reactes2015npm命令将是:

npm install --save-dev babel-preset-stage-0 \
    babel-plugin-transform-class-properties \
    babel-plugin-transform-es2015-classes \
    babel-plugin-transform-es2015-object-super \
    babel-plugin-transform-runtime 

您需要从 Logging 库中导入 logger,如下所示:

import logger from 'logging-Lib';

查看更多:https : //www.npmjs.com/package/react-file-viewer