npm start or npx webpack failed to compile - javascript

when i try to npm start or npx webpack a project which i build about a simple rich text editor using reactjs,draft.js,webpack,and i encountered a problem that show me the compile information:
ERROR in ./src/index.js
Module not found: Error: Can't resolve '' in 'F:\draft_react\my_react'
# ./src/index.js 25:0-55
i am using npm#6.4.1,webpack#4.32.2,node-v10.15.3.
here is my package.json file details
const webpack = require('webpack');
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist',
hot:true
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
};
and index.js file
import React, { Component } from 'react';
import Editor, { createEditorStateWithText } from 'draft-js-plugins-editor';
import createToolbarPlugin from 'draft-js-static-toolbar-plugin';
import editorStyles from './editorStyles.css';
import 'draft-js-static-toolbar-plugin/lib/plugin.css';
const staticToolbarPlugin = createToolbarPlugin();
const { Toolbar } = staticToolbarPlugin;
const plugins = [staticToolbarPlugin];
const text = 'The toolbar above the editor can be used for formatting text, as in conventional static editors …';
export default class SimpleStaticToolbarEditor extends Component {
state = {
editorState: createEditorStateWithText(text),
};
onChange = (editorState) => {
this.setState({
editorState,
});
};
focus = () => {
this.editor.focus();
};
render() {
return (
<div>
<div className={editorStyles.editor} onClick={this.focus}>
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
plugins={plugins}
ref={(element) => { this.editor = element; }}
/>
<Toolbar />
</div>
</div>
);
}
}
i am new to reactjs framework , i don't know how to solve this error for many hours.Thanks.

Related

Failed to resolve import "React" in npm package and webpack 5

I am developing a npm package and use there webpack 5.
This is my config
const path = require('path') // resolve path
module.exports = {
mode: 'development',
resolve: {
extensions: ['.js', '.jsx'], // we can import without typing '.js or .jsx'
},
entry: {
index: path.join(__dirname, 'src/index.jsx'),
},
output: {
path: path.resolve(__dirname, './dist'),
filename: 'index.js', // for production use [contenthash], for developement use [hash]
library: {
type: 'module',
},
environment: { module: true },
},
experiments: {
outputModule: true,
},
devtool: 'eval',
module: {
rules: [
{
test: /\.(css|scss|sass)$/,
use: [
{
loader: 'style-loader', // creates style nodes from JS strings
},
{
loader: 'css-loader', // translates CSS into CommonJS
},
{
loader: 'sass-loader', // compiles Sass to CSS
},
],
},
{
test: /\.(js|jsx)$/,
exclude: /nodeModules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.(png|svg|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
{
test: /.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
exclude:
/images/ /* dont want svg images from image folder to be included */,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'fonts/',
name: '[name][hash].[ext]',
},
},
],
},
],
},
externals: {
react: 'React',
'react-dom': 'ReactDOM',
},
plugins: [],
}
When I want to import components from this library I get this error:
Failed to resolve import "React" from "..my-package/dist/index.js". Does the file exist?
I think this has something to do with externals react and react-dom. But when I remove the externals from webpack config I get the error that react should be only installed once when using react hooks.
In my main application I am using vite for bundeling but I tried it also with create-react-app and have the same problem.
My Library Component:
import React, { useState } from 'react'
const App = () => {
const [counter, setCounter] = useState(0)
return <div>{counter}</div>
}
export default App
This is how I am using it with npm-link:
import React from "react";
import Test from "my-package";
const App = () => {
return <Test />;
};
export default App;
Here is the repo with the code https://github.com/guitar9/webpack-bug

Vue plugin component with own CSS (style is extracted but not applied)

I am making a Vue plugin that contains SFC with its own styles. I am using webpack4 to bundle. For production I use MiniCssExtractPlugin to extract CSS from SFC to separate file. Everything builds up correctly, style.css is created in dist folder and my plugin is working but seems like css from file is not loaded. Is there a step which I am missing?
Thank you
main.js
import SearchBar from "./components/Searchbar.vue";
const defaultOptions = {};
export let Search = {
install(Vue, options) {
let userOptions = { ...defaultOptions, ...options };
let props = { ...SearchBar.props };
Object.keys(userOptions).forEach(k => {
props[k] = { default: userOptions[k] };
});
Vue.component("SearchBarComponent", { ...SearchBar, props });
}
};
Searchbar.vue
<template>
<div class="search">My search template</div>
</template>
<script>
export default{
}
</script>
<style>
.search{
background-color:blue;
}
</style>
webpack.config.js
let path = require("path");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: "./src/main.js",
output: {
path: path.resolve(__dirname, "./dist"),
libraryTarget: "commonjs2",
publicPath: "/dist/",
filename: "search.min.js"
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: "style.css"
})
],
module: {
rules: [
{
test: /\.vue$/,
loader: "vue-loader"
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: "file-loader",
options: {
name: "[name].[ext]?[hash]"
}
},
{
test: /\.css$/,
use: [
process.env.NODE_ENV !== "production"
? "vue-style-loader"
: MiniCssExtractPlugin.loader,
"css-loader"
]
}
]
}
};
In my project, I just install my plugin from npm repository then I use
import {Search} from "my-search-plugin";
Vue.use(Search);
to import plugin, and then call
<SearchBarComponent>
wherever I need. The component appear successfully but styles and not applied.

React-Router subroutes not displaying

It seems that when webpack builds the file the output can only see the maincard div and none of the contents therein. I'm not sure what's missing as when this is run as npm react-scripts start it works fine. I'm not sure what i'm missing from webpack for this to render correctly. I'm trying to load this into an S3 bucket so it has to be packed with the webpack.
import React from 'react';
import { connect } from 'react-redux';
import { Route, withRouter } from 'react-router-dom';
import { fetchUserList } from "../actions/UserActions";
import { fetchSkillList } from "../actions/SkillActions";
import WelcomeCard from "./WelcomeCard";
import UserSearchCard from "./UserSearchCard";
import AddUserCard from './AddUserCard';
import '../styles/MainCard.css';
class MainCard extends React.Component {
componentDidMount() {
this.props.fetchUserList();
this.props.fetchSkillList();
}
render() {
return (
<div className="main_card">
<Route exact path='/' component={WelcomeCard}/>
<Route path='/list' component={UserSearchCard}/>
<Route path='/new' component={AddUserCard}/>
</div>
);
}
}
const mapDispatchToProps = dispatch => {
return {
fetchUserList: () => dispatch(fetchUserList()),
fetchSkillList: () => dispatch(fetchSkillList())
}
};
export default withRouter( connect(undefined, mapDispatchToProps)(MainCard) );
Webpack Config:
let path = require('path');
let webpack = require('webpack');
const publicPath = '/dist/build/';
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
//Content
entry: './src/index.js',
mode: 'development',
// A SourceMap without column-mappings ignoring loaded Source Maps.
devtool: 'cheap-module-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
}),
//simplifies creation of HTML files to serve your webpack bundles. This is especially useful for webpack bundles that include a hash in the filename which changes every compilation. You can either let the plugin generate an HTML file for you, supply your own template using lodash templates or use your own loader.
new HtmlWebpackPlugin({
title: 'Talent Identification Manager'
}),
//Auto replacement of page when i save some file, even css
new webpack.HotModuleReplacementPlugin(),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
output: {
path: path.join(__dirname, publicPath),
filename: 'main.bundle-0.0.1.js',
publicPath: "/",
sourceMapFilename: 'main.map',
},
devServer: {
port: 3000,
host: 'localhost',
//Be possible go back pressing the "back" button at chrome
historyApiFallback: true,
noInfo: false,
stats: 'minimal',
publicPath: publicPath,
contentBase: path.join(__dirname, publicPath),
//hotmodulereplacementeplugin
hot: true
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules(?!\/webpack-dev-server)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-2'],
plugins: ['syntax-decorators']
}
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
]
}
}
React Router doesn't know that you want to treat /talentidbucket as the base of your site, so you have explicitly tell it so by passing the base path as the basename prop of the BrowserRouter component in production.
class App extends React.Component {
render() {
return (
<BrowserRouter basename="/talentidbucket"> {/* ... */} </BrowserRouter>
);
}
}

How to use React.js with AdonisJs

How can I use React.js in the front-end of my AdonisJs project?
I've tried to install react with npm install react I thought this will works correctly. I made a file app.js with this code:
var React = require('react');
var ReactDOM = require('react-dom');
export default class Index extends Component {
render() {
return (< h1 > hello world! < /h1>)
}
}
ReactDOM.render( < Index / > , document.getElementById('example'))
But this isn't working at all, I don't know what to do more I have searched about how to use React in Adonis but I didn't find anything interesting.
I strongly suggest you to use WebPack for this task.
create a webpack.config.js file in your root directory:
maybe your code need some changes but this is the idea:
const webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var pkgBower = require('./package.json');
module.exports = {
target: "web",
devtool: "source-map",
node: {
fs: "empty"
},
entry: {
'app': path.join(__dirname, 'react-app', 'Index.jsx')
},
resolve: {
modules: [__dirname, 'node_modules', 'bower_components'],
extensions: ['*','.js','.jsx', '.es6.js']
},
output: {
path: path.join(__dirname, 'public', 'src'),
filename: '[name].js'
},
resolveLoader: {
moduleExtensions: ["-loader"]
},
module: {
loaders: [
{
test: /jquery\.flot\.resize\.js$/,
loader: 'imports?this=>window'
},
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react', 'stage-0'],
compact: false
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.woff|\.woff2|\.svg|.eot|\.ttf/,
loader: 'url?prefix=font/&limit=10000'
},
{
test: /\.(png|jpg|gif)$/,
loader: 'url?limit=10000'
},
{
test: /\.scss$/,
loader: 'style!css!sass?outputStyle=expanded'
}
]
},
plugins: [
new ExtractTextPlugin("styles.css"),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new CopyWebpackPlugin([{
from: 'img',
to: 'img',
context: path.join(__dirname, 'react-app')
}, {
from: 'server',
to: 'server',
context: path.join(__dirname, 'react-app')
}, {
from: 'fonts',
to: 'fonts',
context: path.join(__dirname, 'react-app')
}]),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
mangle: true,
sourcemap: false,
beautify: false,
dead_code: true
}),
new webpack.ContextReplacementPlugin(/\.\/locale$/, 'empty-module', false, /js$/)
]
};
Then put your app in your root directory, in a folder react-app/ and your components can go inside that folder:
For example your file: [Index.jsx]
import React from 'react';
import ReactDOM from 'react-dom';
class Index extends Component {
render() {
return (< h1 > hello world! < /h1>)
}
}
ReactDOM.render( < Index / > , document.getElementById('example'));
you don't need to export this Index component in this case, but in case you need to just use export default ComponentName at the end of your component file.
The next step is in your routes file (I'm using AdonisJS 4) but is very similar for the version 3.x
Route.any("*", ({ view, response }) => (
view.render('index')
))
Then your index (.njk, or .edge) file (under resources/views) should look something like this:
<html>
<head>
<link rel="stylesheet" href="/src/styles.css">
<script type="text/javascript" src="/src/app.js"></script>
</head>
<body>
<div id="example"></div>
</body>
</html>
--
You need to install some npm/ packages with npm or yarn,
and remember to run in another terminal window or tab,
webpack -d --watch --progress
Regards.
This works. You are missing React.Component.
var React = require('react');
var ReactDOM = require('react-dom');
export default class Index extends React.Component {
render() {
return (< h1 > hello world! < /h1>)
}
}
ReactDOM.render( < Index / > , document.getElementById('example'))
Alternatively you can use import React, {Component} from 'react'; if you want to use your code structure.
For decoupled use, just build your React app and copy the build to Adonis public folder.

Webpack build React.createClass is not a function

I have a ReactJS application with webpack module builder, following is the configuration in my webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: {
app : './src/scripts/app.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'public')
},
context: __dirname,
resolve: {
extensions: ['.js', '.jsx', '.json', '*']
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
options: {
presets: ['react', 'es2015']
}
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
}
]
}
};
I have following code in my app.js
import React from 'react';
import ReactDOM from 'react-dom';
var MainApp = React.createClass({
render: function(){
return (
<div>
<div>Header component</div>
<div>Boady component</div>
</div>
);
}
});
ReactDOM.render(
<MainApp />,
document.getElementById('container')
);
Now after running the server, when I load my page in browser getting following error:
Uncaught TypeError: _react2.default.createClass is not a function
Attaching screenshot of the error message:
I would like to know more details on this issue, many thanks for the help.
You need to install this npm extension:
npm install create-react-class --save
And then use this code:
var createReactClass = require('create-react-class');
var MainApp = createReactClass({
render: function(){
return (
<div>
<div>Header component</div>
<div>Boady component</div>
</div>
);
}
});
}

Categories