I am new to Reactjs and am started learning it. I have been trying to start a basic hello world program but its failing at compilation level.
Created a start up hello-word program with create-react-app hello-world it gave me a nice folder structure with bunch of files.
And Here you can see the compilation error
Failed to compile
./src/index.js
Module build failed: Error: Failed to load plugin import: Cannot find module
'eslint-plugin-import'
Referenced from:
at Array.forEach (native)
at Array.reduceRight (native)
This error occurred during the build time and cannot be dismissed.
Here the error states cannot find module so i tried to install eslint plugin import ,standard ..etc but still its not worked.
Below is my webpack.config.dev.js
// @remove-on-eject-begin
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @remove-on-eject-end
'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 env = getClientEnvironment(publicUrl);
module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in
DevTools.
// See the discussion in https://github.com/facebookincubator/create-
react-app/issues/343.
devtool: 'cheap-module-source-map',
entry: [
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Next line is not used in dev but WebpackDevServer crashes without it:
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on
Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\/g, '/'),
},
resolve: {
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// @remove-on-eject-begin
// Resolve Babel runtime relative to react-scripts.
// It usually still works on npm 3 without this but it would be
// unfortunate to rely on, as react-scripts could be symlinked,
// and thus babel-runtime might not be resolvable from the source.
'babel-runtime': path.dirname(
require.resolve('babel-runtime/package.json')
),
// @remove-on-eject-end
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-
with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
// Prevents users from importing files from outside of src/ (or
node_modules/).
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-
app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /.(js|jsx)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
// @remove-on-eject-begin
baseConfig: {
extends: [require.resolve('eslint-config-react-app')],
},
ignore: false,
useEslintrc: false,
// @remove-on-eject-end
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
{
test: [/.bmp$/, /.gif$/, /.jpe?g$/, /.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// @remove-on-eject-begin
babelrc: false,
presets: [require.resolve('babel-preset-react-app')],
cacheDirectory: true,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
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` files to keep "css" loader working as it injects
// it's runtime that would otherwise processed through "file"
loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/.js$/, /.html$/, /.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
],
},
],
},
plugins: [
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
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,
},
};
Can any one guide me how to come out of this build error.
I started «Create React App» using npm. I then edited the App.js file — I added the code below for the Hello World and saved it. But it does not work.
I get:
Failed to compile
./src/App.js
Syntax error: C:/Dans/Work 2/Tech/Web Dev/Javascript and jQuery/Reactjs/my-app/src/App.js: Unexpected token (6:12)
4 |
5 | class App extends Component {
> 6 | ReactDOM.render(
| ^
7 | <h1>Hello, world!</h1>,
8 | document.getElementById('root')
9 | );
This error occurred during the build time and cannot be dismissed.
Note: The documentation does not explain how to do the examples using the «Create React App». It works if I follow the section for «Trying Out React». I use my own text editor, using the download HTML file and modifying it for Hello World. See the code at the bottom that works!
I replaced the original code with:
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { ReactDOM.render( <h1>Hello, world!</h1>, document.getElementById('root') ); }
export default App;
The original code:
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to React</h1> </header> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
It works if I follow the section for «Trying Out React». I use my own text editor, using the download HTML file and modifying it for Hello World.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Hello World</title> <link href="C:DansWork 2TechWeb DevJavascript and jQueryReactjsHello worldstyle.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="root"> <!-- This div's content will be managed by React. --> </div> <script type="text/babel"> ReactDOM.render( <h1>Hello, world!</h1>, document.getElementById('root') ); </script> </body> <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script> </html>
#reactjs #react-router
#reactjs #react-router
Вопрос:
В Windows npm run start
работает нормально, но npm run start
на m1 выдает ошибку.
Зачем вы это делаете?
Failed to compile
./node_modules/react-router-config/esm/react-router-config.js
Attempted import error: 'Switch' is not exported from 'react-router'.
This error occurred during the build time and cannot be dismissed.
"react-router-dom": "^5.3.0", "react-scripts": "^4.0.1",
Это app.js код.
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import routes from "./Routes";
import {renderRoutes} from "react-router-config";
import theme from './theme';
import {ThemeProvider} from "styled-components";
export default function App() {
return (
<BrowserRouter>
{renderRoutes(routes)}
</BrowserRouter>
);
};
``
Комментарии:
1.
Switch
заменено наroutes
, если вы используете react-router v6. Так что проверьте это.
Ответ №1:
Если вы случайно обновились react-router-dom
до версии 6, компонент больше не экспортируется Switch
. Он был заменен Routes
компонентом, который должен непосредственно переносить / отображать Route
компоненты.
- Замените компонент
Switch
наRoutes
компонент.import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; ... function App() { return ( <Router> <Routes> <Route path="/" element={<Home/>} /> </Routes> </Router> ); }
Выполните обновление с версии 5, чтобы перенести ваш проект с версии 5 на версию 6 в вашем приложении, поскольку было довольно много изменений в API компонентов.
- Вернитесь к
react-router-dom
версии 5.- Выполнить
npm un -s react-router-dom
- Выполнить
npm i -s react-router-dom@5.3.0
- Выполнить
Комментарии:
1. У меня есть часть, которую необходимо обновить немедленно, мне действительно нужно перенести? Будут ли ошибки даже со старой версией?
2. @skksks Я бы вернулся к версии 5, пока не буду готов к обновлению, особенно если для этого есть нетривиальная работа.
3.
react-router-dom
это версия 5, но я продолжаю получатьswitch
ошибки.4. Если вы использовали RRDv5, то он, безусловно, должен экспортировать
Switch
компонент. Из каталога вашего проекта запуститеnpm list react-router-dom
, чтобы узнать, какая на самом деле установленная версия. Если вы используете версию 5, убедитесь, что вы остановили / уничтожили все средства просмотра кода / горячие перезагрузки и перезапустили свой сервер разработки.5. Похоже, у вас установлены две версии? Вы работаете в моно-репозитории? Какой бы из них ни был на версии 6, его следует откатить до версии 5, чтобы соответствовать всем обычаям в вашем приложении.
Ответ №2:
Похоже, проблема связана с версией react-router-dom
Написанный вами код, похоже, совместим с version 5
установленным вами пакетом version 6
. Пожалуйста, проверьте.
В version 6
Switch
заменяется наRoutes
- Поведение маршрутов по умолчанию — точное соответствие маршрутам.
component={Loader}
теперь должно быть записано какelement={<Loader />}
useHistory
заменяется наuseNavigate
.- Порядок, в котором мы перечисляем маршруты, не имеет значения. теперь алгоритм выбирает наилучшее возможное соответствие.
Шаги по обновлению до версии 6
npm uninstall react-router-dom
npm install react-router-dom@6
Затем следуйте приведенному ниже руководству, чтобы внести изменения в свой код. Он должен начать работать нормально.
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
function App() {
return (
<Router basename={process.env.PUBLIC_URL}>
<Routes>
<Route path="/" element={<Home/>} />
<Route path="/dashboard" element={<Dashboard/>} />
<Route path="/*" element={<NotFoundPage/>} />
</Routes>
</Router>
);
}
Кроме того, рекомендуется использовать basename={process.env.PUBLIC_URL}
для установки общедоступного URL-адреса через .env
file.
Другой способ решить эту проблему
Другим способом было бы вернуться к версии 5, но я настоятельно рекомендую вам перейти на версию 6, поскольку она предлагает меньший размер пакета, лучший выбор маршрута, улучшенный стиль кодирования и гораздо более интуитивно понятный способ кодирования вложенных маршрутов.
Ссылки
- Руководство по обновлению до версии 6
- Обновление до версии v6 Учебное пособие
Комментарии:
1. У меня есть часть, которую необходимо обновить немедленно, мне действительно нужно перенести? Будут ли ошибки даже со старой версией?
2. Старая версия содержит ошибки. Особенно при обработке 404 маршрутов. У меня были случаи, когда рендеринг двух компонентов для обновления до версии 6 едва ли занимает 30 минут. Я бы сказал, что это стоит времени, поскольку повышает производительность в целом.
-
omidd1315
- Posts: 1
- Joined: 08 Apr 2018, 20:26
hello
when we import Editor with this line of code.
Code: Select all
import {Editor} from 'primereact/components/editor/Editor';
This error occurred during the build time and cannot be dismissed.
Failed to compile
./node_modules/primereact/components/editor/Editor.js
Module parse failed: Unexpected token (10:24)
You may need an appropriate loader to handle this file type.
| export class Editor extends Component {
|
| static defaultProps = {
| id: null,
| value: null,
-
Natethecoder2
- Posts: 2
- Joined: 21 Mar 2019, 23:18
10 May 2019, 15:42
I have a similar problem. Even after i updated my package.json to «quill»: «1.3.3»,
here’s my error message.
error in ./node_modules/quill/dist/quill.snow.css
Module parse failed: Unexpected token (7:0)
You may need an appropriate loader to handle this file type.
| * Copyright (c) 2013, salesforce.com
| */
> .ql-container {
| box-sizing: border-box;
| font-family: Helvetica, Arial, sans-serif;
@ ./node_modules/primereact/components/editor/Editor.js 16:0-36
@ ./node_modules/primereact/editor.js
-
Natethecoder2
- Posts: 2
- Joined: 21 Mar 2019, 23:18
17 May 2019, 17:01
As I investigated this is more related to a next.js issue and SSR not giving quill a «document» object to work with. We are moving on to slate.
-
Who is online
Users browsing this forum: No registered users and 0 guests