【问题标题】:how to solve this error You may need an appropriate loader to handle this file type如何解决此错误您可能需要适当的加载程序来处理此文件类型
【发布时间】:2018-06-10 14:22:32
【问题描述】:

我在使用这个库时遇到了这个错误https://github.com/react-native-web-community/react-native-web-linear-gradient/

错误链接 https://github.com/react-native-web-community/react-native-web-linear-gradient/issues/1 错误详情: 模块解析失败:意外令牌 (5:22) 您可能需要适当的加载程序来处理此文件类型。

我的网页包:

'use strict';

const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');

const publicPath = '/';
const publicUrl = '';
const env = getClientEnvironment(publicUrl);

module.exports = {
  devtool: 'cheap-module-source-map',
  entry: [
    require.resolve('./polyfills'),
    require.resolve('react-dev-utils/webpackHotDevClient'),
    paths.appIndexJs,
  ],
  output: {
    pathinfo: true,
    filename: 'static/js/bundle.js',
    chunkFilename: 'static/js/[name].chunk.js',
    publicPath: publicPath,
    devtoolModuleFilenameTemplate: info =>
      path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
  },
  resolve: {
    modules: ['node_modules', paths.appNodeModules].concat(
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
    alias: {
      'babel-runtime': path.dirname(
        require.resolve('babel-runtime/package.json')
      ),
      'react-native': 'react-native-web',
      'react-native-linear-gradient': 'react-native-web-linear-gradient'
    },
    plugins: [
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
    ],
  },
  module: {
    strictExportPresence: true,
    rules: [
      {
        test: /\.(js|jsx|mjs)$/,
        enforce: 'pre',
        use: [
          {
            options: {
              formatter: eslintFormatter,
              eslintPath: require.resolve('eslint'),
              baseConfig: {
                extends: [require.resolve('eslint-config-react-app')],
              },
              ignore: false,
              useEslintrc: false,
            },
            loader: require.resolve('eslint-loader'),
          },
        ],
        include: paths.appSrc,
      },
      {
        oneOf: [
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: require.resolve('url-loader'),
            options: {
              limit: 10000,
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
          {
            test: /\.(js|jsx|mjs)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              babelrc: false,
              presets: [require.resolve('babel-preset-react-app')],
              cacheDirectory: true,
            },
          },
          {
            test: /\.css$/,
            use: [
              require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                },
              },
              {
                loader: require.resolve('postcss-loader'),
                options: {
                  ident: 'postcss',
                  plugins: () => [
                    require('postcss-flexbugs-fixes'),
                    autoprefixer({
                      browsers: [
                        '>1%',
                        'last 4 versions',
                        'Firefox ESR',
                        'not ie < 9', // React doesn't support IE8 anyway
                      ],
                      flexbox: 'no-2009',
                    }),
                  ],
                },
              },
            ],
          },
          {
            exclude: [/\.js$/, /\.html$/, /\.json$/],
            loader: require.resolve('file-loader'),
            options: {
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new InterpolateHtmlPlugin(env.raw),
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
    }),
    new webpack.NamedModulesPlugin(),
    new webpack.DefinePlugin(env.stringified),
    new webpack.HotModuleReplacementPlugin(),
    new CaseSensitivePathsPlugin(),
    new WatchMissingNodeModulesPlugin(paths.appNodeModules),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ],
  node: {
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty',
  },
  performance: {
    hints: false,
  },
};

提出问题的班级:

import React, { PureComponent } from 'react';
import { View } from 'react-native';

export default class LinearGradient extends PureComponent {
  static defaultProps = {
    start: {
      x: 0.5,
      y: 0,
    },
    end: {
      x: 0.5,
      y: 1,
    },
    locations: [],
    colors: [],
  };

  state = {
    width: 1,
    height: 1,
  };

  measure = ({ nativeEvent }) =>
    this.setState({
      width: nativeEvent.layout.width,
      height: nativeEvent.layout.height,
    });

  getAngle = () => {
    // Math.atan2 handles Infinity
    const angle =
      Math.atan2(
        this.state.width * (this.props.end.y - this.props.start.y),
        this.state.height * (this.props.end.x - this.props.start.x)
      ) +
      Math.PI / 2;
    return angle + 'rad';
  };

  getColors = () =>
    this.props.colors
      .map((color, index) => {
        const location = this.props.locations[index];
        let locationStyle = '';
        if (location) {
          locationStyle = ' ' + location * 100 + '%';
        }
        return color + locationStyle;
      })
      .join(',');

  render() {
    return (
      <View
        style={[
          this.props.style,
          { backgroundImage: `linear-gradient(${this.getAngle()},${this.getColors()})` },
        ]}
        onLayout={this.measure}
      >
        {this.props.children}
      </View>
    );
  }
}

static defaultProps 和 ()=> 造成了错误,那么可能出了什么问题?

【问题讨论】:

  • 你能从你的 webpack 配置中清除文本,它可能更容易阅读吗?
  • @JasonAllshorn 我删除了所有注释行

标签: reactjs react-native webpack babeljs react-native-web


【解决方案1】:

这就是如何将 webpack 配置为load assets,例如图片(pngssvgsjpgs 等):

  1. npm install --save-dev file-loader
  2. 将此添加到webpack.config.jsmodule.exports.rules 下:
{
  test: /\.(png|svg|jpg|gif)$/,
  use: ["file-loader"]
}

现在,当您从 './my-image.png' 导入 MyImage 时,该图像将被处理并添加到您的输出目录中,MyImage 变量将包含该图像处理后的最终 URL。

【讨论】:

  • 有与此等价的 GatsbyJS 吗?只能找到npm install gatsby-plugin-force-file-loader? Gatsby 不喜欢 npm install --save-dev file-loader 所以寻找解决方法!提前致谢
【解决方案2】:

我认为这是因为 ES7 特性。您是否已安装 stage-0 并将其添加到您的 .babelrcwebpack.config.js 文件中?

这里是如何做到的:

npm i --save-dev babel-preset-stage-0 然后你应该将它包含在webpack.config.js 文件中,如下所示:

loader: "babel-loader", // or just "babel"
query: {
  presets: [ <other presets>, 'stage-0']
}

或者添加到.babelrc文件:

{
  "presets": ["stage-0"]
}

更新

正如我之前所说,这个问题属于 ES7 功能。似乎 webpack 无法解析 static 模块中的 static 关键字。所以我做了什么来解决这个问题:

  1. 我将源代码从react-native-web-linear-gradient 复制到我自己的名为LinearGradient 的组件中。我没有更改其中的任何内容。
  2. 如上所述,我安装了stage-0 并将其添加到.babelrc
  3. 稍后我不使用react-native-web-linear-gradient,而是使用我的LinearGradient 组件。

因此,我的页面上出现了渐变。 git项目链接。

希望对您有所帮助!

【讨论】:

  • 如果你帮助了我,我会通过 stackoverflow 赏金给你 50 分
  • Reson 我用“react-native-web-linear-gradient”替换了你的导入,但仍然没有修复
  • 我希望修复从 node_modules 文件夹中的模块导入
【解决方案3】:

部分修复 >>

步骤:

图书馆上的1-npm install babel babel-cli --save-dev

2-我添加"transpile": "babel src/index.js --out-file src/index-transpiled.js"package.json 脚本中

3-yarn transpile

4-我将 ES5 文件移到了我的代码中并且它工作了

更新 - 全面修复

包含我的 src 文件夹和 babel 的库

// Process JS with Babel.
          {
            test: /\.(js|jsx|mjs)$/,
            include: [
              /src\/*/,
              /node_modules\/react-native-/,
            ],
            loader: require.resolve('babel-loader'),
            options: {
              babelrc: false,
              presets: [require.resolve('babel-preset-react-native')],
              cacheDirectory: true
            }
          },

【讨论】:

  • 这个修复对我不起作用。我得到的错误是Module parse failed: Unexpected token (10:2) You may need an appropriate loader to handle this file type. const pop = payload =&gt; ({ type: POP, ...payload, });
  • @Vikram 我不确定你的代码有什么问题
  • 我正在使用react-navigationreact-native-web(打字稿)。当我尝试包含 react-navigation 模块时,它会出错。都与传播运算符有关。
  • 我尝试在config/webpack.config.dev.js 中添加babel-plugin-transform-object-rest-spreadbabel-preset-stage-0;但没有一个工作。
  • 我没有解决办法尝试在stackoverflow上提问
猜你喜欢
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多