import observable or whatever from mobx not found - javascript

I created a React.js project from scratch, with my own webpack config etc... I try to put mobx inside the project but I can not because import doesn't work.
as you can see:
I tried everything like import mobx from 'mobx or import { observable } from 'mobx/lib/mobx' the last solution works but it is not a good practice as the official document says : https://mobx.js.org/best/pitfalls.html
I share the webpack config, package.json, .babelrc
webpack config :
import path from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
module.exports = {
entry: path.join(__dirname,'src','index.js'),
output: {
path: path.join(__dirname,'build'),
filename: 'index.bundle.js',
},
mode: process.env.NODE_ENV || 'development',
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
},
devServer: {
contentBase: path.join(__dirname,'src'),
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.(css|scss)$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
],
},
{
test: /\.(jpg|jpeg|png|gif|mp3|svg)$/,
loaders: ['file-loader'],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname,'public','index.html'),
filename: 'index.html',
favicon: path.join(__dirname,'public','favicon.png'),
}),
],
};
package.json :
{
"name": "client",
"version": "1.0.0",
"description": "front-end built in reactjs for the js under pressure project",
"main": "index.js",
"license": "MIT",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "yarn lint && babel-node ./node_modules/webpack/bin/webpack --mode production",
"start:dev": "yarn lint && babel-node ./node_modules/webpack-dev-server/bin/webpack-dev-server --mode development --open",
"lint": "babel-node ./node_modules/eslint/bin/eslint.js \"src/**/*.js\" \"src/**/*.jsx\" --fix"
},
"devDependencies": {
"#babel/core": "^7.4.5",
"#babel/node": "^7.4.5",
"#babel/plugin-proposal-class-properties": "^7.4.4",
"#babel/plugin-proposal-decorators": "^7.4.4",
"#babel/preset-env": "^7.4.5",
"#babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.6",
"css-loader": "^2.1.1",
"eslint": "^5.16.0",
"eslint-plugin-eslint-comments": "^3.1.1",
"eslint-plugin-jest": "^22.6.4",
"eslint-plugin-react": "^7.13.0",
"html-webpack-plugin": "^3.2.0",
"mobx": "^5.10.0",
"mobx-react": "^6.0.3",
"mobx-react-devtools": "^6.1.1",
"node-sass": "^4.12.0",
"path": "^0.12.7",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.33.0",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.6.0"
},
"dependencies": {
"#material-ui/core": "^4.0.2",
"#material-ui/icons": "^4.0.1",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-ace": "^7.0.2",
"react-dom": "^16.8.6"
}
}
babelrc :
{
"presets": [
"#babel/env",
"#babel/react"
],
"plugins": [
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
}
and what i'm trying :
mobx/index.js :
import { observable } from 'mobx';
class AppStore {
#observable test = 'test';
/* #observable level = 0;
#observable check = 0;
#observable skiped = false;
#observable state = 0;
#observable count = 0;
#observable levels= [];
#observable test = [];
*/
/* #action.bound
levelUp() {
this.level += 1;
}
#action.bound
startTimer() {
setInterval(() => {
this.count += 1;
}, 1000);
}
#action.bound
skiped() {
this.skip = !this.skip;
}
#action.bound
startTest() {
this.state = 1;
}
#action.bound
endTest() {
this.state = 2;
clearInterval(this.startTime());
}*/
}
export default AppStore;
and the src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { App } from 'containers/app.jsx';
import AppStore from 'mobx/index.js';
const store = new AppStore();
/**
* DOM component - setup main component into root div
* #reactProps {none} none - none
* #desc Entry point of the react app
* #extends {ReactDOM}
* #public
* #version 1.0
* #since 1.0
*/
/*eslint react/jsx-filename-extension: 0*/
ReactDOM.render((
<App store={ store } />
),
document.getElementById('root'));
Any help will be greatly appreciated.
Thanks for your time and happy coding!!!

Here's your problem:
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
},
It wouldn't be a problem, except that you have to be careful not to name your directories the same as npm packages. If you change the mobx directory to, say, store, module resolution should work properly again.

Related

Error with Webpack version 5.1.2 "MainTemplate.hooks.startup has been removed"

I'm having an issue with a ReactJS + Webpack + Express I was watching in a tutorial.
After I finished setting up the following files:
server.js
webpack.config.js
.babelrc
package.json
After trying to run the server in the VS Code bash terminal. I get the following output:
Error: MainTemplate.hooks.startup has been removed (use RuntimeGlobals.startup instead) at Object.tap
Here's the code on all the above files
server.js:
import express from 'express';
import webpack from 'webpack';
import WebpackDevMiddleware from 'webpack-dev-middleware';
import webpackConfig from '../webpack.config';
// init packages
const app = express();
// set server
app.set('port', process.env.PORT || 8080);
// middleware
app.use(WebpackDevMiddleware(webpack(webpackConfig)));
// routes
app.get('/', (request, response) => {
response.send('Hello, user');
});
app.get('/demo', (request, response) => {
response.json({demo: 'Hello, demo user' });
});
// listen on port
app.listen(app.get('port'), () => {
console.log('server on port ', app.get('port'));
});
webpack.config.js:
import webpack from 'webpack';
import htmlWebpackPlugin from 'html-webpack-plugin';
import LiveReloadPlugin from 'webpack-livereload-plugin';
export default {
entry: './src/client/index.js',
output: {
path: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
},
{
test: /\.scss$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: { sourceMap: true }
},
{
loader: 'sass-loader',
options: { sourceMap: true }
}
]
}
]
},
plugins: [
new htmlWebpackPlugin({ template: './src/client/index.html' }),
new LiveReloadPlugin()
],
}
.babelrc:
{
"presets": [ "env", "react" ]
}
package.json:
{
"name": "nodejs-practice",
"version": "1.0.0",
"description": "NodeJS Practice with React, MongoDB and NodeJS",
"main": "main.js",
"scripts": {
"dev": "nodemon --exec babel-node src/server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^5.0.0",
"html-webpack-plugin": "^4.5.0",
"node-sass": "^4.14.1",
"nodemon": "^2.0.5",
"sass-loader": "^10.0.3",
"style-loader": "^2.0.0",
"webpack": "^5.1.2",
"webpack-dev-middleware": "^3.7.2",
"webpack-livereload-plugin": "^2.3.0"
},
"dependencies": {
"express": "^4.17.1",
"react": "^16.14.0",
"react-dom": "^16.14.0"
}
}
I want to know what the problem might be since I was looking for some answers but couldn't find anything.
I think that I might have to downgrade several of the dependencies.
Thanks.
It's because webpack-livereload-plugin is using a deprecated webpack API
Here's the issue tracking how to fix it

Webpack exclude 3rd party libraries installed via npm

As for fun I am developing my own html/css admin panel theme migrating from old codebase into webpack as an attempt to make it more modular. Also I use it as an excuse for learning webpack and making my frontend code more test friendly.
My webpack config is:
const path = require('path');
module.exports = {
entry: [
__dirname+"/assets/js/panel.js",
],
output: {
path: __dirname+'/www',
publicPath: '/',
filename: 'panel.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
],
},
{
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.scss$/,
use: [
{
loader:'style-loader',
},
// Translates CSS into CommonJS
{
loader:'css-loader'
},
// Compiles Sass to CSS
{
loader:'sass-loader'
},
],
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}
]
}
],
},
devServer: {
contentBase: path.join(__dirname, 'www'),
compress: true,
port: 8000
}
};
And my assets/js/panel.js is considted of the following code:
// 3rd party libs
import $ from 'jquery';
import bsBreakpoints from 'bs-breakpoints'
import 'bootstrap';
import _ from 'lodash';
import '#fortawesome/fontawesome-free/js/fontawesome'
import '#fortawesome/fontawesome-free/js/solid' // https://fontawesome.com/icons?d=gallery&s=solid&m=free
import '#fortawesome/fontawesome-free/js/regular' // https://fontawesome.com/icons?d=gallery&s=regular&m=free
import '#fortawesome/fontawesome-free/js/brands' // https://fontawesome.com/icons?d=gallery&s=brands&m=free
// Rest of the code is here
Also my package.json is consisted by this settings:
{
"name": "ellakcy_admin",
"version": "1.0.0",
"description": "Admin HTML/CSS template using Bootstrap",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack-dev-server --compress"
},
"keywords": [
"html",
"css",
"admin"
],
"author": "Cypriot FOSS Community",
"license": "GPL",
"dependencies": {
"#fortawesome/fontawesome-free": "^5.4.1",
"bootstrap": "^4.3.1",
"bs-breakpoints": "^1.0.0",
"jquery": "^3.4.1",
"jquery-ui-dist": "^1.12.1",
"popper.js": "^1.16.0",
"saas": "^1.0.0",
"script-loader": "^0.7.2",
"lodash": ">=4.17.13",
"lodash.template": ">=4.5.0"
},
"devDependencies": {
"#babel/core": "^7.7.2",
"#babel/preset-env": "^7.7.1",
"autoprefixer": "^9.7.1",
"babel-loader": "^8.0.6",
"css-loader": "^3.2.0",
"file-loader": "^4.2.0",
"node-sass": "^4.13.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.0.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0",
"clean-css": ">=4.1.11"
}
}
So, many themes are being shipped without its 3rd party dependencies so when I build with the js and css with webpack how I can exclude them? I mean it is pointless to ship eg. fontawesome or bootstrap.

"You may need an appropriate loader to handle this file type"

I want to use react-leaflet in my react project but I don't understand how to make it work I always get an error when I try to compile my code:
ERROR in ./node_modules/react-leaflet/src/index.js 5:7
Module parse failed: Unexpected token (5:7)
You may need an appropriate loader to handle this file type.
| export { LeafletConsumer, LeafletProvider, withLeaflet } from './context'
|
> export type {
| LeafletContext,
| LatLng,
I don't understand what I did wrong :( I tried the example from the git repo and it did work so I don't know what is the difference between my project and the git. I checked the installation guide and I made everything required.
Here is my webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const htmlWebpackPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
});
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options: {
modules: true,
importLoaders: 1,
localIdentName: "[name]_[local]_[hash:base64]",
sourceMap: true,
minimize: true
}
}
]
}
]
},
plugins: [htmlWebpackPlugin]
};
My package.json :
{
"name": "simple_webpack",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"scripts": {
"start": "webpack-dev-server --mode development",
"build": "webpack --mode production"
},
"author": "Drigtime",
"license": "",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.11",
"html-webpack-plugin": "^3.1.0",
"style-loader": "^0.20.3",
"webpack": "^4.2.0",
"webpack-cli": "^2.0.13",
"webpack-dev-server": "^3.1.1"
},
"dependencies": {
"leaflet": "^1.3.3",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-leaflet": "^2.0.0"
}
}
And the actual code that doesn't work
import React from "react";
import ReactDOM from "react-dom";
import { Map, TileLayer } from "react-leaflet/src";
const Index = () => {
return (
<Map>
<TileLayer
attribution="&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors"
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</Map>
);
};
ReactDOM.render(<Index />, document.getElementById("index"));
It looks like your import should be:
import { Map, TileLayer } from "react-leaflet";
Simple fix!

Module build failed: Error: Couldn't find preset "transform-class-properties" relative to directory

I've tried putting an arrow function in my class which failed to compile.
I've read that I should install https://www.npmjs.com/package/babel-plugin-transform-class-properties
Now I'm getting the error:
Module build failed: Error: Couldn't find preset
"transform-class-properties" relative to directory
"/home/luke/Documents/myProject"
I've tried the solutions suggested in these posts (and others)
Webpack + Babel: Couldn't find preset "es2015" relative to directory
Error: Couldn't find preset "es2015" relative to directory
My current setup is as follows:
/app/components/App.js
import React from 'react'
import { Switch, Route, BrowserRouter as Router } from 'react-router-dom'
class App extends React.Component{
sayHello = name => `Hello ${name}!`
render(){
return(
<Router>
<div >
...
</div>
</Router>
)
}
}
export default App
/package.json
{
"name": "um-web",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --open",
"build": "NODE_ENV='production' webpack -p"
},
"babel": {
"presets": [
"env",
"react",
"es2015",
"transform-class-properties"
]
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.0.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "^1.6.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.4",
"html-webpack-plugin": "^2.28.0",
"style-loader": "^0.18.2",
"webpack": "^2.6.1",
"webpack-dev-server": "^2.4.5"
},
"dependencies": {
"amazon-cognito-identity-js": "^1.19.0",
"axios": "^0.16.2",
"d3": "^4.9.1",
"lodash": "^4.17.4",
"moment": "^2.18.1",
"prop-types": "^15.5.10",
"query-string": "^4.3.4",
"react": "^15.6.1",
"react-dimensions": "^1.3.0",
"react-dom": "^15.6.1",
"react-measure": "^2.0.2",
"react-router-dom": "^4.1.1",
"recharts": "^1.0.0-alpha.1",
"semantic-ui-react": "^0.69.0"
}
}
/webpack.config.js
var path = require('path')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var webpack = require('webpack')
var config = {
entry: './app/index.js',
output:{
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module:{
rules:[
{ test: /\.(js)$/, use: 'babel-loader'},
{ test: /\.css$/, use: ['style-loader', 'css-loader']}
]
},
devServer: {
historyApiFallback: true
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
}
if(process.env.NODE_ENV === 'production'){
config.plugins.push(
new webpack.DefinePlugin({
'process.env' : {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}
}),
new webpack.optimize.UglifyJsPlugin()
)
}
module.exports = config
transform-class-properties is a plugin not a preset, so you should put it in your babel plugin config.
Here is an example .babelrc
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions", "safari >= 7"],
"uglify": true
},
"modules": false
}],
"react"
],
"plugins": [
["transform-class-properties", { "spec": true }],
"transform-decorators",
"transform-object-rest-spread",
"react-hot-loader/babel"
]
}
And the explanation of this plugin:
https://babeljs.io/docs/plugins/transform-class-properties/
Hope this helps.
babel-plugin-transform-class-properties is a plugin not a preset. When you list it under presets, Babel will look for the module with the babel-preset- prefix in addition to the literal module name. See Plugin/Preset Paths for details.
You need to put it under plugins, as the Usage in the README shows.
"babel": {
"presets": [
"env",
"react"
],
"plugins": [
"transform-class-properties"
]
},
I also removed the es2015 preset, because it is deprecated in favour of env which contains everything that es2015 does and more.

React can't be found

index.js:
import react from 'react';
import {render} from 'react-dom';
render(
<h1>Hello World!</h1>,
document.getElementById('root')
);
package.json:
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --progress --watch",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Callum Linington",
"license": "ISC",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2",
"whatwg-fetch": "^2.0.3"
},
"devDependencies": {
"babel-cli": "^6.24.0",
"babel-preset-es2015": "^6.24.0",
"babel-preset-react": "^6.23.0",
"babel-core": "^6.24.0",
"babel-loader": "^6.4.1",
"babel-preset-env": "^1.3.2",
"bluebird": "^3.5.0",
"eslint": "^3.19.0",
"webpack": "^2.3.2",
"webpack-dev-server": "^2.4.2"
}
}
Webpack config:
var webpack = require('webpack');
var packages = require('./package.json');
var path = require('path');
module.exports = {
entry: {
main: './src/index.js',
vendor: Object.keys(packages.dependencies)
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor' // Specify the common bundle's name.
})
],
devtool: "cheap-eval-source-map",
devServer: {
contentBase: path.join(__dirname, "dist"),
publicPath: '/',
port: 9000
},
module: {
rules: [
{
test: /\.js?$/,
use: [ 'babel-loader', ],
exclude: /node_modules/
}
]
}
};
Webpack output:
Chrome Dev Output:
It is crutial to name imported React class starting with capital letter. You first line should be: import React from 'react';. That is because all JSX tags will be converted by Babel to something like React.createElement(....) and React is not there. Exactly what console output tells you.

Categories

Resources