reactjs 如何解决此错误您可能需要一个适当的加载程序来处理此文件类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48034538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to solve this error You may need an appropriate loader to handle this file type
提问by amorenew
I got this error with this library https://github.com/react-native-web-community/react-native-web-linear-gradient/
我在这个库中遇到了这个错误https://github.com/react-native-web-community/react-native-web-linear-gradient/
the error link https://github.com/react-native-web-community/react-native-web-linear-gradient/issues/1details of error: Module parse failed: Unexpected token (5:22) You may need an appropriate loader to handle this file type.
错误链接https://github.com/react-native-web-community/react-native-web-linear-gradient/issues/1错误 详情:模块解析失败:意外令牌 (5:22) 您可能需要一个合适的加载器来处理这种文件类型。
my webpack:
我的网络包:
'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,
},
};
the class who make the problem:
提出问题的班级:
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 defaultPropsand ()=> make the bug so what could be wrong?
静态 defaultProps和 ()=> 产生了错误,那么可能有什么问题呢?
采纳答案by amorenew
Partial fix>>
部分修复>>
Steps:
脚步:
1-npm install babel babel-cli --save-devon the library
1-npm install babel babel-cli --save-dev在图书馆
2-I add "transpile": "babel src/index.js --out-file src/index-transpiled.js"in package.jsonscripts
2,我想补充"transpile": "babel src/index.js --out-file src/index-transpiled.js"的package.json脚本
3-yarn transpile
3-yarn transpile
4-I moved the ES5 file to my code and it worked
4-我将 ES5 文件移动到我的代码中并且它工作正常
Update - Full Fix
更新 - 完全修复
I includedmy src folder and the libraries to babel too
我也包含了我的 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
}
},
回答by The Reason
I think this is because of ES7feature. Do you have stage-0installed & added to your .babelrcor webpack.config.jsfile?
我认为这是因为ES7特性。您是否已stage-0安装并添加到您的.babelrc或webpack.config.js文件中?
Here how you can do it:
在这里你可以怎么做:
npm i --save-dev babel-preset-stage-0And then you should include it into webpack.config.jsfile like below:
npm i --save-dev babel-preset-stage-0然后你应该将它包含到webpack.config.js文件中,如下所示:
loader: "babel-loader", // or just "babel"
query: {
presets: [ <other presets>, 'stage-0']
}
Or add it to .babelrcfile:
或将其添加到.babelrc文件中:
{
"presets": ["stage-0"]
}
UPDATE
更新
As I said earlier the issue belongs to ES7feature. Seems like webpackcan not resolve statickeyword within react-native-web-linear-gradientmodule. So what I did to fix this issue:
正如我之前所说,这个问题属于ES7特性。似乎webpack无法解析模块static内的关键字react-native-web-linear-gradient。所以我做了什么来解决这个问题:
- I copied the source code from
react-native-web-linear-gradientinto my own component calledLinearGradient. I didn't change anything within it. - I installed
stage-0and added it to.babelrcas i described above. - Later instead of using
react-native-web-linear-gradienti use myLinearGradientcomponent.
- 我将源代码复制
react-native-web-linear-gradient到我自己的名为LinearGradient. 我没有改变它里面的任何东西。 - 我按照上面的描述安装
stage-0并添加了它.babelrc。 - 后来
react-native-web-linear-gradient我使用我的LinearGradient组件而不是使用我的组件。
As a result i got gradient on my page. gitproject link.
结果我的页面上出现了渐变。git项目链接。
Hope it will help!
希望它会有所帮助!
回答by Menelaos Kotsollaris
This is how webpack can be configured to load assets, such as images (pngs, svgs, jpgsand so on):
这是的WebPack可以如何被配置为负载资产,诸如图像(pngs,svgs,jpgs等等):
npm install --save-dev file-loader- Add this in the
webpack.config.js, under themodule.exports.rules:
npm install --save-dev file-loader- 将其添加到
webpack.config.js, 下module.exports.rules:
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
}
Now, when you import
MyImagefrom'./my-image.png', that image will be processed and added to your output directory and theMyImagevariable will contain the final url of that image after processing.
现在,当您
MyImage从导入时'./my-image.png',该图像将被处理并添加到您的输出目录中,并且该MyImage变量将包含处理后该图像的最终 url。

