What loader I need for JSX compile? - reactjs

Hi I am new doing webpackconfig for compile my react js component and I am triying to compile it for publish in npm(I am unsing react I started using jsc classes etc but always the same error, so I translate to js, but again the same error :/ I'm lost) :
my babelrc:
{
"presets": ["es2015", "react"]
}
my package.json:
{
"name": "react-chat-bot42",
"version": "0.6.7",
"private": false,
"description": "An ES6 npm module Chat Bot!",
"main": "dist/index.js",
"scripts": {
"build": "babel src -d dist",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "IƱigo Romero",
"license": "MIT",
"keywords": [
"Chabot",
"react"
],
"dependencies": {
"#babel/plugin-syntax-jsx": "^7.12.13",
"#babel/preset-react": "^7.12.13",
"babel-preset-es2015": "^6.24.1",
"extract-text-webpack-plugin": "^3.0.2",
"path": "^0.12.7",
"react": "^16.14.0",
"react-dom": "^17.0.1",
"webpack": "^4.29.6"
},
"devDependencies": {
"#babel/core": "^7.12.13",
"#babel/preset-env": "^7.12.13",
"autoprefixer": "^10.2.4",
"babel-cli": "^6.26.0",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "^8.2.2",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^5.0.2",
"html-webpack-plugin": "^5.0.0",
"webpack-cli": "^4.5.0"
},
"repository": {
"type": "git",
"url": "https://github.com/InigoRomero/npm-Chat-Bot"
}
}
my webpack.config.js:
const path = require('path')
module.exports = {
entry: path.resolve(__dirname, 'src', 'index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js'
}
}
The Error when I try to "webpack --mode=development" for compile:
ERROR in ./src/index.js 96:6
Module parse failed: Unexpected token (96:6)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| return (
> <div id="container" className="container">
| <div id="chat" className="chat">
| <div id="messages" className="messages"></div>
My source code:
import React, {Component} from 'react';
import {Dprompts, DReplies, DnotFound} from './DefaultConstants'
//import './DefaultStyle.css'
const reactChatBot = props => {
let
prompts = props.Prompts ? props.Prompts : Dprompts,
Replies = props.Replies ? props.Replies : DReplies,
notFound = props.notFound ? props.notFound : DnotFound,
botIcon = props.botIcon,
userIcon = props.userIcon,
input = '',
text = '',
product = '';
window.onload = function() {
let inputField = document.getElementById("input");
inputField.addEventListener("keydown", (e) => {
if (e.code === "Enter") {
input = inputField.value;
inputField.value = "";
output();
}
});
}
function output() {
let product2;
let text2 = input.toLowerCase().replace(/[^\w\s]/gi, "").replace(/[\d]/gi, "").trim();
text2 = text2
.replace(/ a /g, " ")
.replace(/i feel /g, "")
.replace(/whats/g, "what is")
.replace(/please /g, "")
.replace(/ please/g, "")
.replace(/r u/g, "are you");
text = text2;
if (compare()) {
product2 = compare();
} else if (text2.match(/thank/gi)) {
product2 = "You're welcome!"
} else {
product2 = notFound[Math.floor(Math.random() * notFound.length)];
}
product = product2;
addChat();
}
function compare() {
let reply;
let replyFound = false;
for (let x = 0; x < prompts.length; x++) {
for (let y = 0; y < prompts[x].length; y++) {
if (prompts[x][y] === text) {
let replies = Replies[x];
reply = replies[Math.floor(Math.random() * replies.length)];
replyFound = true;
break;
}
}
if (replyFound) {
break;
}
}
return reply;
}
function addChat() {
const messagesContainer = document.getElementById("messages");
let userDiv = document.createElement("div");
userDiv.id = "user";
userDiv.className = "user response";
userDiv.innerHTML = `<img src="`+ userIcon +`" class="avatar"><span>${text}</span>`;
messagesContainer.appendChild(userDiv);
let botDiv = document.createElement("div");
let botImg = document.createElement("img");
let botText = document.createElement("span");
botDiv.id = "bot";
botImg.src = botIcon;
botImg.className = "avatar";
botDiv.className = "bot response";
botText.innerText = "...";
botDiv.appendChild(botText);
botDiv.appendChild(botImg);
messagesContainer.appendChild(botDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight - messagesContainer.clientHeight;
setTimeout(() => {
botText.innerText = `${product}`;
}, 2000
)
}
return (
<div id="container" className="container">
<div id="chat" className="chat">
<div id="messages" className="messages"></div>
<input id="input" type="text" placeholder="Say something..." autoComplete="off" autoFocus={true} />
</div>
</div>
);
};
export default reactChatBot;
and IF I try the webpack with this loader:
var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
}
}
I got this error:
Error: Plugin/Preset files are not allowed to export objects, only functions. In C:\Users\SapoArmado\Desktop\npm-Chat-Bot\node_modules\babel-preset-es2015\lib\index.js
Thanks for your time!

Does your source file have a .js or .jsx extension? If it contains JSX syntax it should be .jsx or else compiler will complain

Related

React: does not match the corresponding name on disk/ emotion

error:
./src/App.tsx
Cannot find file: 'emotion-react.browser.esm.js' does not match the corresponding name on disk: 'C:\Users\gabrielti\Documents\emasa-management\node_modules\#emotion\react\dist\Emasa-Management'.
I use a mono repo structure, which is as follows
packages / client
packages / server
Mono repo package.json:
{
"name": "xemasa_monorepo",
"version": "1.0.0",
"main": "index.js",
"repository": "https://github.com/sptGabriel/x-Management.git",
"private":true,
"workspaces":{
"packages": [
"packages/*"
]
},
"author": "Gabriel Costa Cerqueira <Gabrielcerqueira96#hotmail.com>",
"license": "MIT",
"devDependencies": {
"husky": "^4.3.0"
},
"husky": {
"hooks": {
"prepare-commit-msg": "exec < /dev/tty && git cz --hook || true",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
}
Client package.json:
{
"name": "#emasa_monorepo/client",
"version": "0.1.0",
"dependencies": {
"#emotion/babel-preset-css-prop": "^11.0.0",
"#emotion/react": "^11.1.2",
"#emotion/styled": "^11.0.0",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"#types/styled-system": "^5.1.10",
"axios": "^0.21.0",
"class-validator": "^0.12.2",
"history": "^5.0.0",
"jsonwebtoken": "^8.5.1",
"lodash.get": "^4.4.2",
"mobx": "^6.0.4",
"mobx-react-lite": "2.2.2",
"mobx-state-tree": "^4.0.2",
"polished": "^4.0.5",
"prop-types": "^15.7.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-hamburger-menu": "^1.2.1",
"react-icons": "^4.1.0",
"react-router-dom": "^6.0.0-beta.0",
"react-scripts": "4.0.1",
"react-spinners": "^0.9.0",
"styled-system": "^5.1.5",
"typescript": "^4.1.2",
"universal-cookie": "^4.0.4",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"type-check": "tsc --project tsconfig.json --pretty --noEmit",
"lint": "eslint --ext js,jsx,ts,tsx --fix",
"prettier-format": "prettier --config .prettierrc ./src/**/*.{ts,tsx} --write"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/plugin-proposal-decorators": "^7.12.1",
"#types/jest": "^26.0.15",
"#types/lodash.get": "^4.4.6",
"#types/node": "^14.14.10",
"#types/react": "^17.0.0",
"#types/react-dom": "^17.0.0",
"#types/react-hamburger-menu": "^0.0.3",
"#types/styled-components": "^5.1.4",
"#types/universal-cookie": "^2.2.0",
"#typescript-eslint/eslint-plugin": "^4.9.0",
"#typescript-eslint/parser": "^4.9.0",
"eslint": "^7.14.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-config-prettier": "^6.15.0",
"eslint-import-resolver-typescript": "^2.3.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-react": "^7.21.5",
"eslint-plugin-react-hooks": "^4.2.0",
"lint-staged": "^10.5.2",
"prettier": "^2.2.1",
"typescript": "^4.1.2"
},
"babel": {
"plugins": [
"transform-decorators-legacy",
"transform-class-properties"
],
"presets": [
"react-app"
]
}
}
babelrc
{
"presets": [
"react-app",
"#babel/preset-env",
"#babel/preset-react",
{
"runtime": "automatic",
"importSource": "#emotion/react"
}
],
"plugins": [
"#emotion/babel-plugin",
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
}
app.jsx:
import React from 'react'
import { observer } from 'mobx-react-lite'
import { ThemeProvider } from '#emotion/react'
import { useAppTheme } from './shared/utils/useAppTheme'
import GlobalReset from './shared/utils/cssReset'
const App: React.FC = observer(() => {
const { theme } = useAppTheme()
return (
<ThemeProvider theme={theme}>
<GlobalReset />
<div>a</div>
</ThemeProvider>
)
})
export default App
file: emotion-react.browser.esm.js exists on :
enter image description here
emotion-react.browser.esm.js code:
import { createElement, useContext, useRef, useLayoutEffect } from 'react';
import '#emotion/cache';
import { h as hasOwnProperty, E as Emotion, c as createEmotionProps, w as withEmotionCache, T as ThemeContext } from './emotion-element-4fbd89c5.browser.esm.js';
export { C as CacheProvider, T as ThemeContext, a as ThemeProvider, u as useTheme, w as withEmotionCache, b as withTheme } from './emotion-element-4fbd89c5.browser.esm.js';
import '#babel/runtime/helpers/extends';
import '#emotion/weak-memoize';
import 'hoist-non-react-statics';
import '../isolated-hoist-non-react-statics-do-not-use-this-in-your-code/dist/emotion-react-isolated-hoist-non-react-statics-do-not-use-this-in-your-code.browser.esm.js';
import { insertStyles, getRegisteredStyles } from '#emotion/utils';
import { serializeStyles } from '#emotion/serialize';
import { StyleSheet } from '#emotion/sheet';
var pkg = {
name: "#emotion/react",
version: "11.1.2",
main: "dist/emotion-react.cjs.js",
module: "dist/emotion-react.esm.js",
browser: {
"./dist/emotion-react.cjs.js": "./dist/emotion-react.browser.cjs.js",
"./dist/emotion-react.esm.js": "./dist/emotion-react.browser.esm.js"
},
types: "types/index.d.ts",
files: [
"src",
"dist",
"jsx-runtime",
"jsx-dev-runtime",
"isolated-hoist-non-react-statics-do-not-use-this-in-your-code",
"types/*.d.ts",
"macro.js",
"macro.d.ts",
"macro.js.flow"
],
sideEffects: false,
author: "mitchellhamilton <mitchell#mitchellhamilton.me>",
license: "MIT",
scripts: {
"test:typescript": "dtslint types"
},
dependencies: {
"#babel/runtime": "^7.7.2",
"#emotion/cache": "^11.0.0",
"#emotion/serialize": "^1.0.0",
"#emotion/sheet": "^1.0.1",
"#emotion/utils": "^1.0.0",
"#emotion/weak-memoize": "^0.2.5",
"hoist-non-react-statics": "^3.3.1"
},
peerDependencies: {
"#babel/core": "^7.0.0",
react: ">=16.8.0"
},
peerDependenciesMeta: {
"#babel/core": {
optional: true
},
"#types/react": {
optional: true
}
},
devDependencies: {
"#babel/core": "^7.7.2",
"#emotion/css": "11.0.0",
"#emotion/css-prettifier": "1.0.0",
"#emotion/server": "11.0.0",
"#emotion/styled": "11.0.0",
"#types/react": "^16.9.11",
dtslint: "^0.3.0",
"html-tag-names": "^1.1.2",
react: "16.14.0",
"svg-tag-names": "^1.1.1"
},
repository: "https://github.com/emotion-js/emotion/tree/master/packages/react",
publishConfig: {
access: "public"
},
"umd:main": "dist/emotion-react.umd.min.js",
preconstruct: {
entrypoints: [
"./index.js",
"./jsx-runtime.js",
"./jsx-dev-runtime.js",
"./isolated-hoist-non-react-statics-do-not-use-this-in-your-code.js"
],
umdName: "emotionReact"
}
};
var jsx = function jsx(type, props) {
var args = arguments;
if (props == null || !hasOwnProperty.call(props, 'css')) {
// $FlowFixMe
return createElement.apply(undefined, args);
}
var argsLength = args.length;
var createElementArgArray = new Array(argsLength);
createElementArgArray[0] = Emotion;
createElementArgArray[1] = createEmotionProps(type, props);
for (var i = 2; i < argsLength; i++) {
createElementArgArray[i] = args[i];
} // $FlowFixMe
return createElement.apply(null, createElementArgArray);
};
var warnedAboutCssPropForGlobal = false; // maintain place over rerenders.
// initial render from browser, insertBefore context.sheet.tags[0] or if a style hasn't been inserted there yet, appendChild
// initial client-side render from SSR, use place of hydrating tag
var Global = /* #__PURE__ */withEmotionCache(function (props, cache) {
if (process.env.NODE_ENV !== 'production' && !warnedAboutCssPropForGlobal && ( // check for className as well since the user is
// probably using the custom createElement which
// means it will be turned into a className prop
// $FlowFixMe I don't really want to add it to the type since it shouldn't be used
props.className || props.css)) {
console.error("It looks like you're using the css prop on Global, did you mean to use the styles prop instead?");
warnedAboutCssPropForGlobal = true;
}
var styles = props.styles;
var serialized = serializeStyles([styles], undefined, typeof styles === 'function' || Array.isArray(styles) ? useContext(ThemeContext) : undefined);
// but it is based on a constant that will never change at runtime
// it's effectively like having two implementations and switching them out
// so it's not actually breaking anything
var sheetRef = useRef();
useLayoutEffect(function () {
var key = cache.key + "-global";
var sheet = new StyleSheet({
key: key,
nonce: cache.sheet.nonce,
container: cache.sheet.container,
speedy: cache.sheet.isSpeedy
}); // $FlowFixMe
var node = document.querySelector("style[data-emotion=\"" + key + " " + serialized.name + "\"]");
if (cache.sheet.tags.length) {
sheet.before = cache.sheet.tags[0];
}
if (node !== null) {
sheet.hydrate([node]);
}
sheetRef.current = sheet;
return function () {
sheet.flush();
};
}, [cache]);
useLayoutEffect(function () {
if (serialized.next !== undefined) {
// insert keyframes
insertStyles(cache, serialized.next, true);
}
var sheet = sheetRef.current;
if (sheet.tags.length) {
// if this doesn't exist then it will be null so the style element will be appended
var element = sheet.tags[sheet.tags.length - 1].nextElementSibling;
sheet.before = element;
sheet.flush();
}
cache.insert("", serialized, sheet, false);
}, [cache, serialized.name]);
return null;
});
if (process.env.NODE_ENV !== 'production') {
Global.displayName = 'EmotionGlobal';
}
function css() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return serializeStyles(args);
}
var keyframes = function keyframes() {
var insertable = css.apply(void 0, arguments);
var name = "animation-" + insertable.name; // $FlowFixMe
return {
name: name,
styles: "#keyframes " + name + "{" + insertable.styles + "}",
anim: 1,
toString: function toString() {
return "_EMO_" + this.name + "_" + this.styles + "_EMO_";
}
};
};
var classnames = function classnames(args) {
var len = args.length;
var i = 0;
var cls = '';
for (; i < len; i++) {
var arg = args[i];
if (arg == null) continue;
var toAdd = void 0;
switch (typeof arg) {
case 'boolean':
break;
case 'object':
{
if (Array.isArray(arg)) {
toAdd = classnames(arg);
} else {
if (process.env.NODE_ENV !== 'production' && arg.styles !== undefined && arg.name !== undefined) {
console.error('You have passed styles created with `css` from `#emotion/react` package to the `cx`.\n' + '`cx` is meant to compose class names (strings) so you should convert those styles to a class name by passing them to the `css` received from <ClassNames/> component.');
}
toAdd = '';
for (var k in arg) {
if (arg[k] && k) {
toAdd && (toAdd += ' ');
toAdd += k;
}
}
}
break;
}
default:
{
toAdd = arg;
}
}
if (toAdd) {
cls && (cls += ' ');
cls += toAdd;
}
}
return cls;
};
function merge(registered, css, className) {
var registeredStyles = [];
var rawClassName = getRegisteredStyles(registered, registeredStyles, className);
if (registeredStyles.length < 2) {
return className;
}
return rawClassName + css(registeredStyles);
}
var ClassNames = /* #__PURE__ */withEmotionCache(function (props, cache) {
var hasRendered = false;
var css = function css() {
if (hasRendered && process.env.NODE_ENV !== 'production') {
throw new Error('css can only be used during render');
}
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var serialized = serializeStyles(args, cache.registered);
{
insertStyles(cache, serialized, false);
}
return cache.key + "-" + serialized.name;
};
var cx = function cx() {
if (hasRendered && process.env.NODE_ENV !== 'production') {
throw new Error('cx can only be used during render');
}
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return merge(cache.registered, css, classnames(args));
};
var content = {
css: css,
cx: cx,
theme: useContext(ThemeContext)
};
var ele = props.children(content);
hasRendered = true;
return ele;
});
if (process.env.NODE_ENV !== 'production') {
ClassNames.displayName = 'EmotionClassNames';
}
if (process.env.NODE_ENV !== 'production') {
var isBrowser = "object" !== 'undefined'; // #1727 for some reason Jest evaluates modules twice if some consuming module gets mocked with jest.mock
var isJest = typeof jest !== 'undefined';
if (isBrowser && !isJest) {
var globalContext = isBrowser ? window : global;
var globalKey = "__EMOTION_REACT_" + pkg.version.split('.')[0] + "__";
if (globalContext[globalKey]) {
console.warn('You are loading #emotion/react when it is already loaded. Running ' + 'multiple instances may cause problems. This can happen if multiple ' + 'versions are used, or if multiple builds of the same version are ' + 'used.');
}
globalContext[globalKey] = true;
}
}
export { ClassNames, Global, jsx as createElement, css, jsx, keyframes };
I already searched and found nothing about it, I don't know what's going on

Cannot start react module

Getting the following exception when starting the npm.
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.module has an unknown property 'loaders'. These properties are valid:
object { exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, defaultRules?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp?, strictExportPresence?, strictThisContextOnImports? }
-> Options affecting the normal modules (NormalModuleFactory).
var path= require('path');
module.exports = {
entry : './script.jsx',
output : {
path : path.resolve(__dirname,''),
filename: 'transpiled.js'
},
module : {
loaders: [
{
test:/\.jsx?$/,
loaders:'babel-loader',
exclude : /node_modules/,
query : {
presets : ['es2015','react']
}
}
]
}
}
After the updations the code is running but react components are not getting rendered on the screen.
//Update
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test title</title>
</head>
<body>
<div id ="content">
<h1>This is the demo of your web page</h1>
</div>
<script src ="transpiled.js"></script>
</body>
</html>
//webpack config
var path= require('path');
module.exports = {
entry : './script.jsx',
output : {
path : path.resolve(__dirname,'react/index.html'),
filename: 'transpiled.js'
},
module : {
rules: [ // rules rules
{
test: /\.jsx?$/,
loaders: 'babel-loader',
//use:'babel-loader', // use here
exclude : /node_modules/,
query : {
presets : ['es2015','react']
}
}
]
}
}
//script.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class MyComponent extends React.Component {
render() {
return (
<h2>Hello World !!!</h2>
);
}
}
ReactDom.render(
<MyComponent/>,document.getElementById('content')
);
//package.json
{
"name": "reactjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"it": "webpack-dev-server --hot"
},
"author": "chetan",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^4.5.0",
"webpack-cli": "^2.0.14",
"webpack-dev-middleware": "^3.1.2",
"webpack-dev-server": "^3.1.3",
"webpack-hot-middleware": "^2.21.2"
},
"dependencies": {
"react": "^16.3.1",
"react-dom": "^16.3.1",
"webpack-sources": "^1.1.0"
}
}
You need to replace keyword loaders to keyword rules. And in each rules object replace loaders to keyword use.
module.exports = {
entry : './script.jsx',
output : {
path : path.resolve(__dirname,''),
filename: 'transpiled.js'
},
module : {
rules: [ // rules rules
{
test:/\.jsx?$/,
use:'babel-loader', // use here
exclude : /node_modules/,
query : {
presets : ['es2015','react']
}
}
]
}
}
Edit
Now your component not rendered on the screen because output.path in webpack config incorrect. It should be like this:
output : {
path : path.resolve(__dirname),
filename: 'transpiled.js'
}
Because script tag in your html reference in root of the project:
<script src="transpiled.js"></script>
Your webpack.config file is in the wrong format
var path = require('path');
module.exports = {
entry: './script.jsx',
output: {
path: path.resolve(__dirname, ''),
filename: 'transpiled.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
loaders: 'babel-loader',
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
// your preset
]
}
}
]
}
]
}
}
See more here

Webpack config to consume an API with no CORS header

I need to consume a public API with no CORS header in it. I'm very new in webpack so i take this approach by readind articles. The scaffolding is provided by the company. This is a second part from a exercise for a job.
I been looking for hours and nothing seems to help. I always get the same response No 'Access-Control-Allow-Origin' header is present on the requested resource ...
This is my webpack.config.js at the moment
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './client/index.html',
filename: 'index.html',
inject: 'body'
})
module.exports = {
entry: './client/index.js',
output: {
path: path.resolve('dist'),
filename: 'index_bundle.js'
},
module: {
rules: [
{ test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{ test: /\.jsx$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.(sass)$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader"
}]
},
{
test: /\.html/,
loader: 'raw-loader'
},
],
},
plugins: [HtmlWebpackPluginConfig],
devServer: {
contentBase: './src/public',
port: 1184,
proxy: {
'https://api.mcmakler.de/v1/advertisements': {
target: 'https://api.mcmakler.de/v1/advertisements',
secure: false
}
}
},
resolve: {
extensions: [ '.js', '.jsx' ]
}
};
my dependecies are:
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.9",
"eslint": "^4.0.0",
"file-loader": "^1.1.8",
"html-webpack-plugin": "^2.28.0",
"node-sass": "^4.7.2",
"raw-loader": "^0.5.1",
"sass-loader": "^6.0.6",
"style-loader": "^0.20.2",
"url-loader": "^0.6.2",
"webpack": "^2.6.1",
"webpack-dev-server": "^2.4.5"
},
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"yarn": "^1.3.2"
}
and this is my jsx file which is a simple component to render an advertisement
import React from 'react';
import House from './index.jsx';
const publicApi = "https://api.mcmakler.de/v1/advertisements";
export default class Dinamic extends React.Component {
constructor () {
super();
this.state = {
advertisements: [],
};
}
componentDidMount() {
fetch(publicApi)
.then((results) => {
console.info('results: ', results);
return results.blob();
})
.then ((data) => {
console.info('data: ', data);
const advertisements = data.results.map((ad) => {
return (
<div key="ads.results" >
<p>{ad.title}</p>
</div>
)
});
this.setState({ advertisements });
})
.catch((err) => {
console.error("boom!: ", err);
})
}
render() {
return (
<div className="container-fluid">
<div className="container">
<h1>Dinamic</h1>
<div className="row">
{this.state.advertisements}
</div>
</div>
</div>
);
}
}
Did i miss something important or this is completely wrong?
Disclaimer: The job is for Web UI developer, but i think this is also fun to learn
The browsers don't allow reading forbidden headers like 'set-cookie' from response and browser also does not allow setting 'Cookie' header. So I resolved this issue by reading cookie in onProxyRes method and saving it in a variable and setting the saved cookie on following request in onProxyReq method.
let cookie;
devConfig.devServer = {
proxy: {
'*': {
target: https://target.com,
secure: false,
changeOrigin: true,
onProxyReq: (proxyReq) => {
proxyReq.setHeader('Cookie', cookie);
},
onProxyRes: (proxyRes) => {
Object.keys(proxyRes.headers).forEach((key) => {
if (key === 'set-cookie' && proxyRes.headers[key]) {
const cookieTokens = split(proxyRes.headers[key], ',');
cookie = cookieTokens.filter(element => element.includes('JSESSIONID')).join('');
}
});
},
},
},
}

transpiled code (babel) seems not working in Browser

Hi I'm working on an existing app which needs enhancements. The app is built using angularJS, Babel, webpack. I struggled running the app locally and finally succeeded in running it after making changes to how we call a basedirective (like below) which was using babel next generation javascript notation to regular notation (a compiler is present on babel site to do this).
function filtersDirective() {
return {
...baseDirective(template, FiltersCtrl),
...{
bindToController: {
customers: '=',
regions: '=',
managers: '=',
projects: '=',
statuses: '=',
},
},
}
}
Now the issue is I'm able to run this app locally and also able to build the bundle files (app.bundle.js, vendor.bundle.js, manifest.bundle.js) but when I deploy these files to my test server, the console error is like below.
ReferenceError: production is not defined
at dispatchXhrRequest (vendor.bundle.js:24340)
at new Promise (<anonymous>)
at xhrAdapter (vendor.bundle.js:24325)
at dispatchRequest (vendor.bundle.js:92054)
at <anonymous>
vendor.bundle.js:65932
TypeError: Cannot read property 'map' of undefined
at https://#domain/cdn/3.2.1/vendor.bundle.js:5202:31
at https://#domain/cdn/3.2.1/vendor.bundle.js:5090:28
at f1 (https://#domain/cdn/3.2.1/vendor.bundle.js:5070:27)
at https://#domain/cdn/3.2.1/vendor.bundle.js:4920:35
at https://#domain/cdn/3.2.1/vendor.bundle.js:4920:35
at https://#domain/cdn/3.2.1/vendor.bundle.js:4920:35
at https://#domain/cdn/3.2.1/vendor.bundle.js:4672:27
at getAttributeFromProjects (https://#domain/cdn/3.2.1/app.bundle.js:117:10)
at MainController (https://#domain/cdn/3.2.1/app.bundle.js:127:21)
at invoke (https://#domain/cdn/3.2.1/vendor.bundle.js:58052:17) <div ui-view="" class="ng-scope">
My Traspiled app.bundle.js looks like below
webpackJsonp([1], {
/***/
101:
/***/
(function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_0_deepmerge__ = __webpack_require__(69);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_0_deepmerge___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_deepmerge__);
const baseConfig = {
title: 'Test Dashboard',
dashboard: {
title: 'Test Report',
subtitle: 'Weekly Highlights'
},
header: {
title: 'Company Confidential',
nav: 'Test'
}
}
let config = baseConfig
if (window.AppConfig) {
if (window.AppConfig.config) {
config = __WEBPACK_IMPORTED_MODULE_0_deepmerge___default.a(baseConfig, window.AppConfig.config)
}
}
const {
title,
dashboard,
header,
statusBar
} = config
/* harmony export (immutable) */
__webpack_exports__["c"] = title;
/* harmony export (immutable) */
__webpack_exports__["a"] = dashboard;
/* unused harmony export header */
/* unused harmony export statusBar */
/* harmony default export */
__webpack_exports__["b"] = (config);
/***/
}),
/***/
222:
/***/
(function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */
__webpack_require__.d(__webpack_exports__, "b", function() {
return resolve;
});
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_0_ramda__ = __webpack_require__(36);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_0_ramda___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_ramda__);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_1_angular__ = __webpack_require__(7);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_1_angular___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_angular__);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_2__utils__ = __webpack_require__(4);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_3__services_api__ = __webpack_require__(99);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_4__appConfig_config__ = __webpack_require__(101);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_5__dashboard_html__ = __webpack_require__(479);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_5__dashboard_html___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5__dashboard_html__);
/* harmony reexport (default from non-hamory) */
__webpack_require__.d(__webpack_exports__, "c", function() {
return __WEBPACK_IMPORTED_MODULE_5__dashboard_html___default.a;
});
Which is very different from previous version of app.bundle.js which is on prod server which looks like below
webpackJsonp([1], {
/***/
10:
/***/
(function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getWebpartData = undefined;
var _keys = __webpack_require__(124);
var _keys2 = _interopRequireDefault(_keys);
var _deepmerge = __webpack_require__(76);
var _deepmerge2 = _interopRequireDefault(_deepmerge);
var _utils = __webpack_require__(4);
var _majorMilestones = __webpack_require__(501);
var _majorMilestones2 = _interopRequireDefault(_majorMilestones);
var _budget = __webpack_require__(502);
var _budget2 = _interopRequireDefault(_budget);
var _projectRisksAndIssues = __webpack_require__(503);
var _projectRisksAndIssues2 = _interopRequireDefault(_projectRisksAndIssues);
var _actionItems = __webpack_require__(504);
var _actionItems2 = _interopRequireDefault(_actionItems);
var _keyDates = __webpack_require__(505);
var _keyDates2 = _interopRequireDefault(_keyDates);
var _gantt = __webpack_require__(506);
var _gantt2 = _interopRequireDefault(_gantt);
var _statusBar = __webpack_require__(507);
var _statusBar2 = _interopRequireDefault(_statusBar);
var _angular = __webpack_require__(6);
var _angular2 = _interopRequireDefault(_angular);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
below is my package.json file for reference
{
"name": "pmrdashboard",
"version": "3.2.1",
"dependencies": {
"#cgross/angular-notify": "2.5.1",
"angular": "1.4.2",
"angular-bootstrap": "~0.12.2",
"angular-chart.js": "^1.0.1",
"angular-gantt": "^1.2.13",
"angular-google-chart": "^0.1.0",
"angular-messages": "~1.4.2",
"angular-moment": "1.0.1",
"angular-pubsub": "^0.2.0",
"angular-resource": "~1.4.2",
"angular-sanitize": "~1.4.2",
"angular-strap": "^2.3.9",
"angular-toastr": "~1.5.0",
"angular-ui-router": "~0.2.15",
"animate.css": "~3.4.0",
"axios": "^0.16.2",
"babel-cli": "^6.24.1",
"babel-core": "^6.24.1",
"babel-polyfill": "^6.23.0",
"babel-runtime": "^6.23.0",
"bootstrap-sass": "3.3.7",
"chart.js": "2.1.0",
"deepmerge": "^1.3.2",
"echo-loader": "0.0.1",
"jquery": "~2.1.4",
"lodash": "^4.13.1",
"moment": "2.10.6",
"ngsticky-puemos": "^0.0.4",
"node-sass": "4.5.3",
"ramda": "^0.22.1"
},
"scripts": {
"dev": "babel-node scripts/cli.js dev",
"serve": "babel-node scripts/cli.js serve",
"build": "babel-node scripts/cli.js build --upload=false --plugins dynamic-import-node",
"deploy": "babel-node scripts/cli.js build",
"serve:prod": "babel-node scripts/cli.js serve:prod",
"serve:optimize": "babel-node scripts/cli.js serve:prod --optimize=true",
"serve:cdn": "babel-node scripts/cli.js serve:prod --usecdn=true"
},
"devDependencies": {
"babel-eslint": "^7.2.3",
"babel-loader": "^7.0.0",
"babel-plugin-angularjs-annotate": "^0.7.0",
"babel-plugin-dynamic-import-node": "^1.0.2",
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.5.1",
"chalk": "^1.1.3",
"clean-webpack-plugin": "0.1.16",
"cross-env": "^5.1.3",
"css-loader": "0.28.1",
"eslint": "2.13.1",
"eslint-config-angular": "^0.5.0",
"eslint-plugin-angular": "^2.4.0",
"execa": "^0.6.3",
"exports-loader": "0.6.4",
"express": "^4.15.3",
"extract-text-webpack-plugin": "2.1.0",
"file-loader": "0.11.1",
"fs-extra": "^3.0.1",
"html-loader": "0.4.5",
"html-webpack-harddisk-plugin": "0.1.0",
"html-webpack-plugin": "2.28.0",
"http-proxy-middleware": "*",
"http-server": "^0.10.0",
"image-webpack-loader": "3.3.1",
"imports-loader": "0.7.1",
"jshint-loader": "^0.8.4",
"raw-loader": "0.5.1",
"resolve-url-loader": "2.0.2",
"rollup": "^0.43.0",
"rollup-plugin-babel": "^2.7.1",
"rollup-plugin-node-resolve": "^3.0.0",
"sass-loader": "6.0.5",
"shelljs": "^0.7.7",
"ssh-webpack-plugin": "^0.1.7",
"style-loader": "0.17.0",
"svg-loader": "0.0.2",
"url-loader": "0.5.8",
"webpack": "3.0.0",
"webpack-dev-server": "^2.5.0",
"yargs": "^8.0.1"
},
"engines": {
"node": ">=0.10.0"
}
}
webpack config files: it's a folder with .babelrc, dev.js, server.js, prod.js, share.js and below is share.js file
const path = require('path')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {
rm
} = require('shelljs')
const pkg = require('../package.json')
const webpack = require('webpack')
const baseChunks = ['config', 'app']
const basePlugins = (chunks, enableHtml) => {
const html = enableHtml ?
[
new HtmlWebpackPlugin({
title: 'PMR Client',
filename: './index.html',
template: './src/client/index.ejs',
chunksSortMode: (a, b) => chunks.indexOf(a.names[0]) - chunks.indexOf(b.names[0]),
alwaysWriteToDisk: true,
env: process.env.NODE_ENV || 'development',
}),
new HtmlWebpackHarddiskPlugin(),
] :
[]
return [
new ExtractTextPlugin('style.css'),
...html,
new webpack.ProvidePlugin({
'window.jQuery': 'jquery',
}),
new webpack.optimize.ModuleConcatenationPlugin(),
]
}
const baseEntries = {
app: './src/app/index.js',
config: `./clients/${process.env.CLIENT}/config.js`,
}
const baseOutput = () => {
const output = {
path: path.join(__dirname, `../dist/cdn/${pkg.version}`),
filename: '[name].bundle.js',
}
if (process.env.NODE_ENV === 'production' && process.env.UPLOAD === 'true') {
output['publicPath'] = `//streamlinedoffice.com/pmr/cdn/${pkg.version}/`
}
return output
}
const sourceMap = (process.env.NODE_ENV === 'production') ? '' : 'sourceMap'
const getBaseConfig = ({
plugins = [],
chunks = [],
entries = baseEntries,
enableHtml = false
} = {}) => {
rm('-rf', path.resolve(__dirname, '../dist'))
const ch = [...baseChunks, ...chunks]
return {
entry: entries,
output: baseOutput(),
target: 'web',
devtool: 'cheap-module-eval-source-map',
plugins: [...basePlugins(ch, enableHtml), ...plugins],
module: {
rules: [{
test: /\.html$/,
use: [{
loader: 'html-loader',
options: {
minimize: true,
root: '../src/assets/images',
},
}, ],
},
{
test: [/src\/app.*\.js$/, /client.*\.js$/],
exclude: /node_modules/,
use: {
loader: 'babel-loader',
// loader:'echo-loader',
},
},
{
test: [/\.css$/, /\.scss$/],
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', `sass-loader?${sourceMap}`],
}),
},
{
test: /bootstrap-sass\/assets\/javascripts\//,
use: 'imports-loader?jQuery=jquery'
},
// Font Definitions
{
test: /\.svg$/,
loader: 'url-loader?limit=65000&mimetype=image/svg+xml&name=public/fonts/[name].[ext]',
},
{
test: /\.woff$/,
loader: 'url-loader?limit=65000&mimetype=application/font-woff&name=public/fonts/[name].[ext]',
},
{
test: /\.woff2$/,
loader: 'url-loader?limit=65000&mimetype=application/font-woff2&name=public/fonts/[name].[ext]',
},
{
test: /\.[ot]tf$/,
loader: 'url-loader?limit=65000&mimetype=application/octet-stream&name=public/fonts/[name].[ext]',
},
{
test: /\.eot$/,
loader: 'url-loader?limit=65000&mimetype=application/vnd.ms-fontobject&name=public/fonts/[name].[ext]',
},
{
test: /\.png$/,
use: {
loader: 'url-loader?limit=8192',
},
},
{
test: /\.(jpe?g|gif)$/i,
use: [
'file-loader?hash=sha512&digest=hex&publicPath=../&name=./img/[hash].[ext]',
{
loader: 'image-webpack-loader',
query: {
gifsicle: {
interlaced: false,
},
progressive: true,
optipng: {
optimizationLevel: 7,
},
bypassOnDebug: true,
},
},
],
},
],
},
}
}
module.exports = getBaseConfig
Below is the script used to build the app.bundle.js, vendor.bundle.js an d manifest.bundle.js files (this file is on scripts/cmds/prod.js)
import {
echo,
head,
execStrict,
ls,
copy,
rmdir,
mkdir
} from '../utils'
import fs from 'fs-extra'
import path from 'path'
import {
rollup
} from 'rollup'
import resolve from 'rollup-plugin-node-resolve'
import babel from 'rollup-plugin-babel'
const compiler = client =>
rollup({
entry: `./clients/${client}/config.js`,
plugins: [
resolve(),
babel({
exclude: 'node_modules/**',
babelrc: false,
presets: [
['env',
{
modules: false,
targets: {
browsers: [
"last 3 versions",
"Explorer 9",
],
},
},
],
],
plugins: ['external-helpers'],
externalHelpers: true
}),
],
}).then(bundle =>
bundle.write({
format: 'cjs',
dest: path.join(__dirname, `../../.tmpClients/${client}/config.js`),
})
)
const getClients = () =>
fs
.readdirSync('./clients')
.filter(file => fs.lstatSync(path.join('./clients', file)).isDirectory())
const handleCommand = async ({
upload = true,
optimize = true
}) => {
echo(head('Building clients...'))
const clients = getClients()
mkdir('./.tmpClients')
const promises = clients.map(client => {
compiler(client)
})
await Promise.all(promises)
echo(head('Run production build'))
await execStrict(
`cross-env UPLOAD=${upload} OPTIMIZE=${optimize} NODE_ENV=production webpack --config webpack/prod.js --progress --colors --define process.env.NODE_ENV="'production'"`
)
echo(head('Copying config files to clients'))
ls('./.tmpClients').forEach(client => {
copy({
origin: `./.tmpClients/${client}/*.js`,
dest: `./dist/clients/${client}`,
})
copy({
origin: `./dist/clients/${client}/index.html`,
dest: `./dist/clients/${client}/default.aspx`,
})
copy({
origin: './src/client/favicon.ico',
dest: `./dist/clients/${client}/`,
})
})
rmdir('./.tmpClients')
}
exports.command = 'build'
exports.describe = 'Create a production build'
exports.handler = handleCommand
exports.builder = {
upload: {
describe: 'Upload the production files to the cdn',
type: 'boolean',
default: true,
},
optimize: {
describe: 'Toggle the production optimizations, useful to check the production build as development',
type: 'boolean',
default: true,
},
}
below is .babelrc in webpack folder:
{
"presets": ["env"],
"plugins": ["transform-object-rest-spread", "dynamic-import-node"]
}
below .babelrc is in global same level as webpack folder
{
"presets": [
["env", {
"targets": {
"browsers": ["last 3 versions","Explorer 9"]
}
}]
],
"plugins": ["transform-runtime", "transform-object-rest-spread",
["angularjs-annotate", {
"explicitOnly": true
}]]
}
if anyone ran into such similar issue are know how to resolve it do share your inputs. Any help is much appreciated. Thanks

React JS : Module Build Failuer, error showing in render colon

I am getting error like this
Module build failed: SyntaxError
It gives me error in colon of render function
Here it is my code :
webpack.config.js
module.exports = {
entry : './main.js',
output : {
path : './',
filename : 'index.js'
},
devServer : {
inline : true,
port : 3333
},
module : {
loaders : [
{
test : /\.js$/,
exclude : /node_modules/,
loader : 'babel',
query :{
presets : ['es2015', 'react']
}
}
]
}
package.json
{
"name": "library",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel": "^6.5.2",
"babel-core": "^6.9.0",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.5.0",
"react": "^15.0.2",
"react-dom": "^15.0.2"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.9.0",
"babel-loader": "^5.3.2"
}
main.js
import React from 'react';
import ReactDom from 'react-dom';
var Heading = React.createClass({
render : function() {
return <th>{this.props.heading}</th>;
}
});
var Headings = React.createClass({
render : function(){
var headings = this.props.headings.map(function(heading) {
return(<Heading heading = {name}/>);
});
return (<thead><tr>{headings}</tr><thead>);
}
});
var Row = React.createClass({
render : function() {
return (
<tr>
<td>{this.props.changeSet.when}</td>
<td>{this.props.changeSet.who}</td>
<td>{this.props.changeSet.description}</td>
</tr>
);
}
});
var Rows = React.createClass({
render : function() {
var rows = this.props.changeSets.map(function(changeSet) {
return(<Row changeSet = {changeSet} />);
});
return <tbody>{rows}</tbody>;
}
});
var App = React.createClass({
render : function() {
return (
<table className='table'>
<Headings headings={this.props.headings} />
<Rows changeSets={this.props.changeSets} />
</table>
);
}
});
/* Data Declaration */
var data = [
{
"when": "2 minutes ago",
"who": "Jill Dupre",
"description": "Created new account"
},
{
"when": "1 hour ago",
"who": "Lose White",
"description": "Added fist chapter"
},
{
"when": "2 hours ago",
"who": "Jordan Whash",
"description": "Created new account"
}
];
var headings = ['When','Who', 'Description'];
/* Call to Render Function for entire app */
ReactDom.render(<App headings={headings} changeSets={data} />, document.getElementById('container'));
Can somebody please provide a solution for it. I have included babel-core also but can't figure out what's wrong.
I tried setting up your code locally and was able to resolve the issue.
I was getting a Module build failed: ReferenceError: [BABEL] - path to file error
The reason is, The node API for babel has been moved to babel-core.So remove the babel dependency from both dependencies and devDependencies, move the babel-loader to your dependencies and clear the devDependencies of your package.json file and reinstall your modules. It should work
There are some syntax errors on
line 20 render : function(){
unclosed tags in line 15 return (<thead><tr>{headings}</tr><thead>);

Resources