Moment is not defined when using React with Webpack - reactjs

I'm in the progress of "Reactifying" a PHP application and am adding a single component to start (with several child components). In addition to the custom components, there are several library dependencies (react-bootstrap, moment, etc).
I'm using webpack to compile it and it compiles correctly and generates the dist/main.js as expected. However, when adding it to the HTML template I get the error "moment is not defined", though the "react-bootstrap" dependencies appear to load correctly. Based on the guidance in https://github.com/palantir/blueprint/issues/959, I tried both import * as moment from 'moment', import moment from 'moment' as well as the const moment = require('moment'); I had previously been using which compiled fine with browserify.
webpack.config.js
const path = require('path')
module.exports = {
mode: 'development',
context: path.resolve(__dirname, 'components'),
entry: './dir/EntryComponent.app.jsx',
resolve: {
extensions: ['.jsx', '.json', '.js']
},
optimization: {
minimize: false
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
}
};
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
Component.jsx
import Collapse from "react-bootstrap/Collapse";
import moment from 'moment';
const Datetime = require('react-datetime');
...
<label>Start</label>
<Datetime
value={this.props.startDate}
placeholder="Start Date"
dateFormat='YYYY-MM-DD'
timeFormat={false}
input={true}
viewDate={moment().subtract(1, 'month')}
onChange={date => this.props.updateStartDate(date)}
closeOnSelect={true}
closeOnTab={true}
viewMode="months"
inputProps={{readonly: 'readonly'}}/>

Related

Addng css files in React project with Webpack 4

I am building a simple React app from scratch using Webpack.
I was finally able to run the dev server and when I tried to apply some styles via CSS, the files wouldn't load and I assume my Webpack 4 configuration is not right.
Here is the code:
webpack.config.js
// const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require('path');
module.exports = {
mode: 'development',
entry: ['./src/index.js'],
resolve: {
extensions: [".js", ".jsx"]
},
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist',
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 8080
},
module: {
rules: [
{
test: /\.js|.jsx$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: ["react"]
}
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(png|jpg)$/,
loader: 'url-loader'
}
]
},
};
My project structure is like this, I will include only src because it lives in the root:
**src**
|_assets
|_componentns
|_styles
|_App.css
|_index.css
App.jsx
index.js
index.html
I would like to be able to add multiple css files for each component I have and apply them, and to be able to style the index the index.html.
Thank you very much for your help.
Your webpack configuration looks fine.
make sure you import the required css files in your components.
import "./App.css";
class App extends Component {
render() {
return (
<div>
<Child />
</div>
);
}
}
All you have to do is import the CSS files when needed as you would a JavaScript module. So if you want to have a style sheet for your whole application, you can import a global stylesheet in your index.js.
import './styles/index.css';
and you can do the same for each component with specific styles
import './styles/App.css'
in which case you might want to setup CSS modules to avoid overlapping class names.
Ok, rookie mistake here, the way I ahve set up webpack is I have to build it first and then run the dev server, no the other way around.
All answers above are valid and helpful, I just forgot to run build after changes.

Storybook doesn't understand import on demand for antd components

I have followed instructions here to get antd working fine with CRA. But while using it from storybook, I was getting an error as:
Build fails against a mixin with message Inline JavaScript is not
enabled. Is it set in your options?
I had fixed that following suggestions on an issue I raised here.
Now, storybook understands antd but not importing components on demand. Is babel has to be configured separately for storybook?
1. On using import { Button } from "antd";
I get this:
2. On using
import Button from "antd/lib/button";
import "antd/lib/button/style";
I get:
Storybook version: "#storybook/react": "^3.4.8"
Dependency: "antd": "^3.7.3"
I have been stuck (again) with this for quite long hours googling things, any help is appreciated. Thanks!
Using Storybook 4, you can create a webpack.config.js file in the .storybook directory with the following configuration:
const path = require("path");
module.exports = {
module: {
rules: [
{
loader: 'babel-loader',
exclude: /node_modules/,
test: /\.js$/,
options: {
presets: ["#babel/react"],
plugins: [
['import', {libraryName: "antd", style: true}]
]
},
},
{
test: /\.less$/,
loaders: [
"style-loader",
"css-loader",
{
loader: "less-loader",
options: {
modifyVars: {"#primary-color": "#d8df19"},
javascriptEnabled: true
}
}
],
include: path.resolve(__dirname, "../")
}
]
}
};
Note that the above snippet includes a style overwriting of the primary button color in antd. I figured, you might want to eventually edit the default theme so you can remove that line in case you do not intend to do so.
You can now import the Button component in Storybook using:
import {Button} from "antd";
without having to also import the style file.
If you are using AntD Advanced-Guides for React and storybook v5 create .storybook/webpack.config.js with the following:
const path = require('path');
module.exports = async ({ config, mode }) => {
config.module.rules.push({
loader: 'babel-loader',
exclude: /node_modules/,
test: /\.(js|jsx)$/,
options: {
presets: ['#babel/react'],
plugins: [
['import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: true
}]
]
},
});
config.module.rules.push({
test: /\.less$/,
loaders: [
'style-loader',
'css-loader',
{
loader: 'less-loader',
options: {
modifyVars: {'#primary-color': '#f00'},
javascriptEnabled: true
}
}
],
include: [
path.resolve(__dirname, '../src'),
/[\\/]node_modules[\\/].*antd/
]
});
return config;
};
Then you can use import { Button } from 'antd' to import antd components.
I'm currently using storybook with antd and i got it to play nice, by using this config in my webpack.config.js file in the .storybook folder:
const { injectBabelPlugin } = require('react-app-rewired');
const path = require("path");
module.exports = function override(config, env) {
config = injectBabelPlugin(
['import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css' }],
config,
);
config.module.rules.push({
test: /\.css$/,
loaders: ["style-loader", "css-loader", ],
include: path.resolve(__dirname, "../")
})
return config;
};

React-Date "SingleDatePicker" not working as expected?

I am using react-dates and trying to implement singledatepicker. All the functionality is working but I dont know why all the default styles are gone. I am also using babel "transform-class-properties"
import React from 'react';
import moment from 'moment'
import 'react-dates/initialize';
import {SingleDatePicker} from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';
const now= moment();
export default class ExpenseForm extends React.Component{
state={
description:'',
note:'',
amount:'',
createdAt:moment(),
calendarFocused:false
}
onDateChange = (createdAt)=>{
this.setState(()=>({createdAt}));
}
onFocusChange =({focused})=>{
this.setState(()=>({calendarFocused:focused}))
}
render(){
return(
<div>
<h3>ExpenseForm</h3>
<form>
<SingleDatePicker
date={this.state.createdAt}
onDateChange={this.onDateChange}
focused={this.state.calendarFocused}
onFocusChange={this.onFocusChange}
/>
</form>
</div>
)
}
}
Here is my Webpack config file and it is loaded with css-loader
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},{
test: /\.s?css$/,
use:['style-loader','css-loader','sass-loader']
}
]
},
devtool:'cheap-module-eval-source-map',
devServer:{
contentBase:path.resolve(__dirname, 'public'),
historyApiFallback:true
}
};
I had exact the same problem when integration react-dates into my project, and I believe the root cause is that the css module in your project also compile the css of react-dates which leads to missing of the style. To solve this problem, you could modify the rule in your module like:
...your original css module rule
exclude: [
/node_modules/
]
after applying this rule, you might encounter another issue which is that these css files can't be properly handled due to being excluded, you should then add another css module to handle those css file that you don't want to mess with, for example:
exports.vendorCss = {
test: /\.(css|scss|sass)$/,
include: [/node_modules/],
loaders: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
},
],
};
and there you have it!! Hope this can help!

ts-loader / css-loader not being able to import/resolve file

Trying to add css modules using style-loader and css-loader. Having a hard time figuring this out. I'm also not sure whether it's ts-loader to blame or css-loader.
webpack.config.js
const path = require('path');
module.exports = env => {
return {
devtool: "inline-source-map",
entry: "./src/index.tsx",
output: {
path: path.resolve(__dirname, "/public"),
filename: "build/app.js"
},
resolve: {
extensions: [".ts", ".tsx", ".js", ".json"],
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader",
},
{
test: /\.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
}
]
}
}
}
component
import styles from "./Main.css"; // TS2307: Cannot find module './Main.css'.
P.S. I tried using the extract-text-webpack-plugin, but that only messed up everything even more making the errors overwhelming
So since this doesn't seem like a popular problem I managed to find the solution. Hope this will help anyone who struggles with ts-loader + css-loader.
1) Add .d.ts file that handles .css extensions
// I put it in root, but could be anywhere
// <root>/defs.d.ts
declare module "*.css" {
var styles: { [key: string]: string };
export = styles
}
2) Since I use Webpack 3.x, change style to style-loader in webpack.config.js
module: {
rules: [
//...
{
test: /\.css$/,
loader: 'style-loader!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
}
]
}
3) Import styles as * in component file
// In Main.tsx
import * as styles from "./Main.css";
// Usage
<div className={styles.nameOfClass} />
4) In tsconfig.json add .d.ts file to the include part. In my case its...
"include": [
"src",
"./defs.d.ts"
],
Restart webpack-dev-server or whatever and it should be good to go (hopefully).
Happy coding!

React + Reactstrap + CSS Modules + Webpack

I've been looking how I can combine the following : ReactJS + ReactStrap and CSS-Modules (react-css-modules and/or boostrap-css-modules), however, I can't seem to piece the three modules together to achieve the desired effect (or find any help online).
The idea behind this is to have the ReactStrap elements available, i.e. :
import React from 'react';
import { Button } from 'reactstrap';
export default (props) => {
return (
<Button color="danger">Danger!</Button>
);
};
but also allow me to use CSS-Modules for the end result being something similar to :
import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './mybutton.css';
class Test extends React.Component {
render () {
return <Button color='danger' styleName='myButton'>Danger</div>;
}
}
export default CSSModules(Table, styles);
where mybutton.css could be something like :
.myButton {
composes: btnPrimary from "bootstrap-css-modules/css/buttons.css";
background-color: dodgerblue;
border-color: dodgerblue;
}
I'm also using Webpack so I don't even know where to begin with regards to using it with Webpack.
Edit :
The way I am using this is as follows :
npm install --save bootstrap#4.0.0-alpha.6
npm install --save reactstrap react-addons-transition-group react-addons-css-transition-group react react-dom
npm install --save bootstrap-css-modules
Here is my webpack config
const webpack = require('webpack');
const path = require('path');
const HtmlwebpackPlugin = require('html-webpack-plugin');
const ROOT_PATH = path.resolve(__dirname);
module.exports = {
devtool: process.env.NODE_ENV === 'production' ? '' : 'source-map',
entry: [
path.resolve(ROOT_PATH, 'app/src/index'),
],
module: {
rules: [
{
enforce: 'pre',
test: /\.jsx?$/,
loader: process.env.NODE_ENV === 'production' ? [] : ['eslint-loader'],
include: path.resolve(ROOT_PATH, 'app'),
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react'],
},
},
{
test: /\.scss$/,
loaders: ['style-loader', 'css-loader', 'sass-loader'],
}],
},
resolve: {
extensions: ['.js', '.jsx'],
},
output: {
path: process.env.NODE_ENV === 'production' ? path.resolve(ROOT_PATH, 'app/dist') : path.resolve(ROOT_PATH, 'app/build'),
publicPath: '/',
filename: 'bundle.js',
},
devServer: {
contentBase: path.resolve(ROOT_PATH, 'app/dist'),
historyApiFallback: true,
hot: true,
inline: true,
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlwebpackPlugin({
title: 'testapp',
}),
],
};
Thanks
#tehOwner ...phew this question was a doozy. I think I accomplished what you were trying to do.
I created a sandbox that can be found here.
DEMO
Basically, you need this npm module in your project to be able to assign multiple CSS classes to a react component using the className property.
And setup your component with a structure that resembles the below
import React, { Component } from 'react';
import { Button } from 'reactstrap';
import CSSModules from 'react-css-modules';
import styles from './MyDangerButton.css';
import cn from 'classnames';
class MyDangerButton extends Component {
render() {
const myFancyDangerButton = cn({
btn: true,
'btn-danger': true,
MyDangerButton: true
});
return (
<div>
<h1>My Fancy Danger Button!</h1>
<Button className={myFancyDangerButton}>Danger Button</Button>
</div>
);
}
}
export default CSSModules(MyDangerButton, styles);
🍺 cheers
Chris
The newest solution is to upgrade the react-script by using:
npm upgrade --latest react-scripts
It supports the CSS module so you don't need to config anything.
What need to do is add .module to the CSS file: from './mybutton.css' to './mybutton.module.css'. And change the import as well:
import styles from './mybutton.module.css';
Using this, we don't need to perform
npm run eject
any more.

Resources