rendering an html file within react - reactjs

I am getting an html file from an external source and wanting to render it within a modal in react. It looks like it is receiving the file properly but I am getting this error.
Module parse failed: Unexpected token (1:0)
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
|
| <script language="javascript" ...
Here is my webpack.config,js file
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const isProduction = process.env.NODE_ENV == 'production';
const stylesHandler = isProduction ? MiniCssExtractPlugin.loader : 'style-loader';
const config = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
},
plugins: [
// Add your plugins here
// Learn more about plugins from https://webpack.js.org/configuration/plugins/
],
module: {
rules: [
{
test: /\.(js|jsx)$/i,
loader: 'babel-loader',
},
{
test: /\.css$/i,
use: [stylesHandler,'css-loader'],
},
{
test: /\.s[ac]ss$/i,
use: [stylesHandler, 'css-loader', 'sass-loader'],
},
{
test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
type: 'asset',
},
{
test: /\.html$/i,
loader: "html-loader",
},
// Add your rules for custom modules here
// Learn more about loaders from https://webpack.js.org/loaders/
],
},
};
module.exports = () => {
if (isProduction) {
config.mode = 'production';
config.plugins.push(new MiniCssExtractPlugin());
} else {
config.mode = 'development';
}
return config;
};
and here is my App.js file where my react code is located.
import './App.css';
import DOMPurify from 'dompurify';
import Modal from 'react-modal';
import htmlFile from './payee-verification-dropin.html'
import { useState } from 'react';
function App() {
const [showModal, setShowModal]= useState(false);
const myHTML = htmlFile;
const mySafeHTML = DOMPurify.sanitize(myHTML);
return (
<div className="App">
<Modal
isOpen={showModal}
onRequestClose={() => setShowModal(false)}
style={{
overlay: {},
content: {
position: "absolute",
top: "10%",
left: "25%",
width: "839px",
height: "81%",
borderRadius: "10px",
backgroundColor: "#FAFAFA",
padding: "0px",
},
}}
>
<div dangerouslySetInnerHTML={{_html: mySafeHTML }} />
<h1>Hello</h1>
</Modal>
<button onClick={() => setShowModal(true)}>CLick</button>
</div>
);
}
export default App;
Lert me know if you need more info to diagnose this problem.
Thank you!
I ran npx webpack init in order to set up webpack and I ran npm install --save-dev html-loader to try and install an html loader.

Related

isomorphic-style-loader doesn't work as it supposed to

Hey I am doing this simple react + SSR project that incorporates the isomorphic-style loader. I followed the step-by-step guide to implement it as detailed here https://www.npmjs.com/package/isomorphic-style-loader but it just doesn't work. The style I made is not showing. Can anyone guide me in fixing this issue?
Here is my webpack config
var path = require('path');
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');
var browserConfig = {
entry: './src/browser/index.js',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/',
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{
test: /\.css$/,
use: [
'isomorphic-style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
'postcss-loader',
],
},
],
},
mode: 'production',
plugins: [
new webpack.DefinePlugin({
__isBrowser__: 'true',
}),
],
};
var serverConfig = {
entry: './src/server/index.js',
target: 'node',
externals: [nodeExternals()],
output: {
path: __dirname,
filename: 'server.js',
publicPath: '/',
},
mode: 'production',
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{
test: /\.css$/,
use: [
'isomorphic-style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
'postcss-loader',
],
},
],
},
plugins: [
new webpack.DefinePlugin({
__isBrowser__: 'false',
}),
],
};
module.exports = [browserConfig, serverConfig];
here is my index.js (server)
import express from 'express';
import cors from 'cors';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter, matchPath } from 'react-router-dom';
import serialize from 'serialize-javascript';
import StyleContext from 'isomorphic-style-loader/StyleContext';
import App from '../shared/App';
import routes from '../shared/routes';
const app = express();
app.use(cors());
app.use(express.static('public'));
app.get('*', (req, res, next) => {
const css = new Set(); // CSS for all rendered React components
const insertCss = (...styles) =>
styles.forEach((style) => css.add(style._getCss()));
const activeRoute = routes.find((route) => matchPath(req.url, route)) || {};
const promise = activeRoute.fetchInitialData
? activeRoute.fetchInitialData(req.path)
: Promise.resolve();
promise
.then((data) => {
const context = { data };
const markup = renderToString(
<StyleContext.Provider value={{ insertCss }}>
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
</StyleContext.Provider>
);
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>SSR with RR</title>
<script src="/bundle.js" defer></script>
<script>window.__INITIAL_DATA__ = ${serialize(data)}</script>
<style type="text/css">${[...css].join('')}</style>
</head>
<body>
<div id="app">${markup}</div>
</body>
</html>
`);
})
.catch(next);
});
app.listen(3000, () => {
console.log(`Server is listening on port: 3000`);
});
here is my index.js (browser)
import React from 'react';
import { hydrate } from 'react-dom';
import App from '../shared/App';
import { BrowserRouter } from 'react-router-dom';
import StyleContext from 'isomorphic-style-loader/StyleContext';
const insertCss = (...styles) => {
const removeCss = styles.map((style) => style._insertCss());
return () => removeCss.forEach((dispose) => dispose());
};
hydrate(
<StyleContext.Provider value={{ insertCss }}>
<BrowserRouter>
<App />
</BrowserRouter>
</StyleContext.Provider>,
document.getElementById('app')
);
and here is a component inside the App.js which uses the css styling that does not work.
import React from 'react';
import { NavLink } from 'react-router-dom';
import style from './css/style.css';
import withStyles from 'isomorphic-style-loader/withStyles';
function Navbar() {
const languages = [
{
name: 'All',
param: 'all',
},
{
name: 'JavaScript',
param: 'javascript',
},
{
name: 'Ruby',
param: 'ruby',
},
{
name: 'Python',
param: 'python',
},
{
name: 'Java',
param: 'java',
},
];
return (
<ul className='navbar'>
{languages.map(({ name, param }) => (
<li key={param}>
<NavLink
activeStyle={{ fontWeight: 'bold' }}
to={`/popular/${param}`}
>
{name}
</NavLink>
</li>
))}
</ul>
);
}
export default withStyles(style)(Navbar);
I faced the same problem. Problem is related with css-loader. By default, css-loader generates JS modules that use the ES modules syntax. isomorphic-style-loader needs a CommonJS modules syntax.
Try this:
{
loader: 'css-loader',
options: {
importLoaders: 1,
esModule: false,
},
}

Has anybody successfully integrated storybook docs with gatsby?

In my Gatsby themes project, I am trying to integrate the storybook using .mdx format.
But the webpack of storybook is not able to convert the .mdx files.
It keeps throwing different errors.
I have tried using with storybook presets and without presets, but there was no solution.
Card Component
import React from 'react';
const Card = () => {
return (
<div className="laptopUp:max-w-lg max-w-sm mx-auto bg-white shadow-lg rounded-lg overflow-hidden">
<div className="sm:flex sm:items-center px-6 py-4">
<img
className="block mx-auto sm:mx-0 sm:flex-shrink-0 h-16 sm:h-24 rounded-full"
src="https://randomuser.me/api/portraits/women/17.jpg"
alt="Woman's Face"
/>
<div className="mt-4 sm:mt-0 sm:ml-4 text-center sm:text-left">
<p className="text-xl leading-tight">Erin Lindford</p>
<p className="text-sm leading-tight text-gray-600">
Customer Support Specialst
</p>
<div className="mt-4">
<button className="text-purple-500 hover:text-white hover:bg-purple-500 border border-purple-500 text-xs font-semibold rounded-full px-4 py-1 leading-normal">
Message
</button>
</div>
</div>
</div>
</div>
);
};
export {Card};
Card Story:
import { Meta, Story, Preview } from '#storybook/addon-docs/blocks';
import {Card} from './card.js';
<Meta title="MDX|Card" component={Card} />
With `MDX` we can define a story for `Card` right in the middle of our
markdown documentation.
<Preview>
<Story name="Demo Card">
<Card />
</Story>
</Preview>
.storybook/config.js
import { configure, addParameters } from '#storybook/react';
import { DocsPage, DocsContainer } from '#storybook/addon-docs/blocks';
import { action } from '#storybook/addon-actions';
import '../main.css';
addParameters({
docs: {
container: DocsContainer,
page: DocsPage,
prepareForInline: (storyFn) => storyFn(),
},
});
// Gatsby's Link overrides:
// Gatsby defines a global called ___loader to prevent its method calls from creating console errors you override it here
global.___loader = {
enqueue: () => {},
hovering: () => {}
};
// Gatsby internal mocking to prevent unnecessary errors in storybook testing environment
global.__PATH_PREFIX__ = '';
// This is to utilized to override the window.___navigate method Gatsby defines and uses to report what path a Link would be taking us to if it wasn't inside a storybook
window.___navigate = pathname => {
action('NavigateTo:')(pathname);
};
configure(require.context('../src', true, /\.stories\.(js|mdx)$/), module);
My webpack config:
// module.exports = ({ config, mode }) => {
// // Transpile Gatsby module because Gastby includes un-transpiled ES6 code.
// config.module.rules[0].exclude = [/node_modules\/(?!(gatsby)\/)/]
// // use installed babel-loader which is v8.0-beta (which is meant to work with #babel/core#7)
// config.module.rules[0].use[0].loader = require.resolve('babel-loader')
// // The next two lines should always reflect the config in jest-preprocess.js until there is a way for Gatsby to expose an internal webpack.config
// // use #babel/preset-react for JSX and env (instead of staged presets)
// config.module.rules[0].use[0].options.presets = [
// require.resolve('#babel/preset-react'),
// require.resolve('#babel/preset-env'),
// ]
// // use #babel/plugin-proposal-class-properties for class arrow functions
// config.module.rules[0].use[0].options.plugins = [
// require.resolve('#babel/plugin-proposal-class-properties'),
// ]
// // https://github.com/gatsbyjs/gatsby/issues/10662:
// // Prefer Gatsby ES6 entrypoint (module) over commonjs (main) entrypoint
// config.resolve.mainFields = ["browser", "module", "main"]
// return config
// }
/* eslint-disable no-param-reassign */
const path = require('path')
const webpack = require('webpack')
const createCompiler = require('#storybook/addon-docs/mdx-compiler-plugin');
// Export a function. Accept the base config as the only param.
module.exports = async ({ config, mode }) => {
const isProduction = mode
// Transpile Gatsby module because Gatsby includes un-transpiled ES6 code.
config.module.rules[0].exclude = [/node_modules\/(?!(gatsby)\/)/]
// use installed babel-loader which is v8.0-beta (which is meant to work with #babel/core#7)
config.module.rules[0].use[0].loader = require.resolve('babel-loader')
// use #babel/preset-react for JSX and env (instead of staged presets)
config.module.rules[0].use[0].options.presets = [
require.resolve('#babel/preset-react'),
require.resolve('#babel/preset-env')
]
// use #babel/plugin-proposal-class-properties for class arrow functions
config.module.rules[0].use[0].options.plugins = [
require.resolve('#babel/plugin-proposal-class-properties'),
require.resolve('babel-plugin-remove-graphql-queries')
]
config.module.rules = config.module.rules.filter(
f => f.test.toString() !== '/\\.css$/'
)
config.module.rules.push(
{
test: /\.(ttf|woff|woff2|eot|svg)$/,
use: 'file-loader?name=[name].[ext]',
exclude: /\.inline.svg$/
},
{
test: /\.(jpg|png|jpeg|jpg)$/,
loader: 'file-loader',
include: path.resolve(__dirname, '../static/')
},
{
test: /\.css$/,
exclude: /\.module\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
localIdentName: 'mod-[hash:base64:8]'
}
},
'postcss-loader'
],
include: path.resolve(__dirname, '../')
},
{
test: /\.story\.mdx$/,
exclude: [/node_modules/],
include: [
path.resolve(__dirname, '../src'),
],
use: [
{
loader: 'babel-loader',
options: {
plugins: ['#babel/plugin-transform-react-jsx']
}
},
{
loader: '#mdx-js/loader',
options: {
compilers: [createCompiler({})]
}
}
],
},
{
test: /\.module\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: true,
localIdentName: '[local]-[hash:base64:5]'
}
},
'postcss-loader'
],
include: path.resolve(__dirname, '../src')
}
)
config.plugins.push(
new webpack.DefinePlugin({
STORYBOOK: JSON.stringify(true),
PRODUCTION: JSON.stringify(isProduction)
})
)
config.resolve.alias['#'] = path.resolve(__dirname, '../src/')
config.resolve.mainFields = ['browser', 'module', 'main']
return config
}
I expect to be able to see the props and mdx stor has a normal story.
Instead getting various errors.
https://user-images.githubusercontent.com/43405939/66821716-83e17300-ef60-11e9-8a89-fc99591954aa.png
Github Issue: https://github.com/storybookjs/storybook/issues/8414
Github repo to reproduce: https://github.com/vinayg-cp/storybook-poc.git

Problems loading CSS properties with React 16.9.0 and "webpack": "^4.39.2"

My application uses React Select (https://github.com/JedWatson/react-select) and for some reason my app is not able to upload its CSS definitions. My webpack is:
var webpack = require('webpack');
// var ExtractTextPlugin = require("extract-text-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = [
{
entry: './ui/moduleTest/entry.js',
output: { path: __dirname + '/public/compiled', filename: 'mod1bundle.js' },
module: {
rules: [
{ test: /\.jsx?$/, loader: 'babel-loader', include: /ui/, query: { presets: ['#babel/preset-env', '#babel/preset-react'] } },
{ test: /\.scss$/,
use: [ 'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader']
},
{ test: /\.css$/i,
use: [ {loader: 'style-loader',
options: { injectType: 'styleTag' } },
'css-loader']
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'styles.css',
})
]
}
];
My code compiles and runs. However, something is not allowing my app to upload the CSS styles defined for React Select.
Respect of React Select, I can only see a label and a textbox like at:
I can not see its other features as a drop down list. My react component is:
render(){
const customStyles = {
option: (provided, state) => ({
...provided,
borderBottom: '1px dotted pink',
color: state.isSelected ? 'red' : 'blue',
padding: 20,
}),
control: () => ({
// none of react-select's styles are passed to <Control />
width: 200,
}),
singleValue: (provided, state) => {
const opacity = state.isDisabled ? 0.5 : 1;
const transition = 'opacity 300ms';
return { ...provided, opacity, transition };
}
}
return(
<div>
<Select id="analistsSelect001"
styles={customStyles}
key={"analistsSelect001"}
name='analistsSelect001'
placeholder='Choose Analyst'
clearable={false}
value={parseStringToSelectFormat(this.state.selectedAnalyst)}
multi={false}
options={parseToSelectFormat(this.props.analystsMaps.get('elemPKList'))}
onChange={this.handle_selectedAnalyst_Change}
searchable
/>
</div>
)
}
I want to add that I was able to import the main css properties using:
import 'react-select/dist/react-select.css';
However, there are some .scss files that need to be processed and I do not know why my webpack is not allowing this to happen. Should I start using an older version of webpack? any ideas on which one?

Config antd with react and webpack

Here is the error I receive:
Uncaught Error: Module parse failed: Unexpected token (15:5)
You may need an appropriate loader to handle this file type.
| /* stylelint-disable at-rule-no-unknown */
| html,
> body {
| width: 100%;
| height: 100%;
at eval (antd.css:1)
at Object../node_modules/antd/dist/antd.css (index.js:228)
at __webpack_require__ (index.js:20)
at eval (App.js:10)
at Module../KQShopping/frontend/src/App.js (index.js:97)
at __webpack_require__ (index.js:20)
at eval (index.js:2)
at Module../KQShopping/frontend/src/index.js (index.js:109)
at __webpack_require__ (index.js:20)
at index.js:84
webpack config file:
const path = require('path');
const fs = require('fs');
const lessToJs = require('less-vars-to-js');
const themeVariables = lessToJs(fs.readFileSync(path.join(__dirname, './ant-theme-vars.less'), 'utf8'));
module.exports = {
module: {
rules: [
{
loader: 'babel-loader',
test: /\.(js|jsx)$/,
exclude: /node_modules/,
options: {
plugins: [
['import', { libraryName: "antd", style: true }]
]
},
},
{
test: /\.less$/,
use: [
{loader: "style-loader"},
{loader: "css-loader"},
{loader: "less-loader",
options: {
modifyVars: themeVariables
}
}
]
}
]
}
};
App.js:
import React from "react";
import ReactDOM from "react-dom";
import { DatePicker, message } from "antd";
import "antd/dist/antd.css";
class App extends React.Component {
state = {
date: null,
};
handleChange = date => {
message.info(`Selected Date: ${date ? date.format("YYYY-MM-DD") : "None"}`);
this.setState({ date });
};
render() {
const { date } = this.state;
return (
<div style={{ width: 400, margin: "100px auto" }}>
<DatePicker onChange={this.handleChange} />
<div style={{ marginTop: 20 }}>
Selected Date: {date ? date.format("YYYY-MM-DD") : "None"}
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
Babel config file:
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["transform-class-properties", ["import", { "libraryName": "antd", "style": "true" }]]
}
I followed multi tutorials and how-tos but I end up with an error every time and I have no idea how to fix this error since I have just started learning about babel and webpack with small experince.
In this problem I followed exactly this docs https://ant.design/docs/react/getting-started and I still end up with an error
In the end, I used CSS, in the webpack config file add this:
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
}
You shouldn't need to import the antd css at the top of App.js. I also think that the babel plugin should have style set to css in the babel config file (that's how our config file is set up anyway!).
[
'import',
{
'libraryName': 'antd',
'style': 'css'
}
]
Our less loader also has javascriptEnabled set to true:
test: /\.less$/,
use: [{
loader: 'style-loader' // creates style nodes from JS strings
},
{
loader: 'css-loader' // translates CSS into CommonJ
},
{
loader: 'less-loader', // compiles Less to CSS
options: {
javascriptEnabled: true
}
}]

React-css-module not working, style returns a blank object

Not sure what I'm doing wrong here, where I console.log(style) it is just a blank object but defined. No errors.
Login.js - component
import React, {Component} from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import CSSModules from 'react-css-modules';
import { Row, Col } from 'antd';
import styles from './Login.css';
import Logo from '../../components/Logo/Logo';
class Login extends Component {
constructor (props) {
super(props);
}
render () {
const {dispatch} = this.props
console.log(styles);
return (
<Row type="flex" justify="space-around" align="middle" className="container">
<Col sm={16} md={16} lg={9}>
<div className={styles.content}>
<h1>Sign In</h1>
<Logo size="large" className="logo" />
</div>
</Col>
</Row>
)
}
}
Login.propTypes = {
data: PropTypes.object,
history: PropTypes.object,
dispatch: PropTypes.func
}
function select (state) {
return {
data: state
}
}
export default connect(select)(CSSModules(Login, styles));
Login.css - nothing special going on here
body {
background-color: #f0f0f0;
}
.container {
width: 100vw;
height: 100vh;
}
.content {
position: relative;
background-color: #ffffff;
padding: 30px 20px 20px 20px;
}
and the webpack.config.js most likely the culprit but I can't seem to figure out the issue
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body'
})
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve('dist'),
filename: 'index_bundle.js'
},
devServer: {
historyApiFallback: true,
},
mode: "development",
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}, {
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader"
}, {
test: /\.jsx?$/,
exclude: /node_modules/,
use: "babel-loader"
}
]
},
plugins: [
HtmlWebpackPluginConfig,
new ExtractTextPlugin({filename: 'style.css'})
]
}
The app compiles and runs fine just the react-css-module isn't namespacing the styles and the styles aren't being applied to the element.
Its seems you are missing in css-loader:
modules: true to enable CSSModules spec for css-loader.
Check the doc.
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader?modules"
}
I had the same problem .it start to work after I add
modules=true
in the webpack.config.js
as follows.
module:{
rules:
[
{
test:/\.css$/,
loader:'style-loader!css-loader?modules=true'
}
]
}

Resources