React Toolbox finding ~react-toolbox/lib/colors - javascript

Im having some issue trying to setting up the webpack with toolbox.
For some reason i dont know why its not working.
My webpack file looks like:
const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: __dirname,
devtool: 'inline-source-map',
entry: {
factigisVE: './static/js/bundles/factigisVE.js',
vendor: [
'webpack-hot-middleware/client'
]
},
output: {
path: path.join(path.join(__dirname, 'dist'), 'js'),
filename: '[name].js',
libraryTarget: "amd",
publicPath: '/'
},
resolve: {
extensions: ['', '.scss', '.css', '.js', '.json','.webpack.js', '.web.js', '.js', '.jsx'],
modulesDirectories: [
'node_modules',
path.resolve(__dirname, './node_modules')
]
},
module: {
loaders: [
{
test: /(\.js|\.jsx)$/,
exclude: /(node_modules)/,
loader: 'babel',
query: { presets: ['es2015', 'stage-0', 'react','stage-2'] }
}, {
test: /(\.scss|\.css)$/,
loader: ExtractTextPlugin.extract('style', 'css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass')
}
]
},
externals: [
function(context, request, callback) {
if (/^dojo/.test(request) ||
/^dojox/.test(request) ||
/^dijit/.test(request) ||
/^esri/.test(request)
) {
return callback(null, "amd " + request);
}
callback();
}
],
devServer: {
inline: true,
port: 443,
host: "127.0.0.1",
historyApiFallback: true
},
devtool: 'source-map',
postcss: [autoprefixer],
sassLoader: {
data: '#import "css/index.scss";',
includePaths: [path.resolve(__dirname, './static')]
},
plugins: [
new ExtractTextPlugin('../css/style.css', { allChunks: true }),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
};
And then my index.scss looks like:
#import "~react-toolbox/lib/colors";
$color-primary: $palette-blue-500;
$color-primary-dark: $palette-blue-700;
The errors that im having are:
Error: File to import not found or unreadable: ~react-toolbox/lib/colors
parent style sheet: I:/proyect/ve/static/css/index.scss on line 1 of static/css/index.scss
> #import "~react-toolbox/lib/colors";
Also my directory looks like: my directory
Any help on whats going on will be really appreciate.
Thanks !

I was able to resolve this problem by removing the ~ from the start of the import.
#import "react-toolbox/lib/colors";
The postcss-import plugin appears to have the same behvaior.

Related

Webpack production build always returns This page is using the development build of React

I am trying to use webpack-4 to get the production build of react (The project is not created usinf Create React App), but not successful. My project is using typescript and using ts-loader and using the version of React 15.6.2.
The current webpack config file
const path = require("path");
module.exports = {
entry: ['./lib/tproj/js/index.ts'],
output: {
filename: './dist/tproj/js/bundle.js'
},
devtool: "source-map",
resolve: {
extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js', '.json']
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: [
/lib\/tests/,
/lib\/tproj\/elasticsearch/,
/lib\/tproj\/expressserver/
],
loader: "ts-loader"
},
{
test: /\.js$/,
enforce: "pre",
loader: "source-map-loader"
}
]
}
};
I have tried modifying it as follows still it's not working.
const path = require("path");
const webpack = require("webpack");
const TerserPlugin = require('terser-webpack-plugin');
var config = {
entry: ['./lib/tproj/js/index.ts'],
output: {
filename: './dist/tproj/js/bundle.js'
},
resolve: {
extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js', '.json']
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: [
/lib\/tests/,
/lib\/tproj\/elasticsearch/,
/lib\/tproj\/expressserver/
],
loader: "ts-loader"
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
}
]
},
mode: 'production',
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
splitChunks: {
chunks: 'all',
}
}
};
module.exports = (env, argv) => {
if (argv.mode === 'development') {
config.devtool = 'source-map';
}
if (argv.mode === 'production') {
config.devtool = 'false';
}
return config;
}
;
Still a newbie to webpack and React.
Thanks in advance for any help or suggestions.
React contains switch in index.js file between dev and prod versions.
Check process.env.NODE_ENV value in your code after build.
In your webpack config, add this to the plugins array.
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
})
This define the proper environment variable for react to run the production build.
var config = {
entry: ['./lib/tproj/js/index.ts'],
output: {
filename: './dist/tproj/js/bundle.js'
},
resolve: {
extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js', '.json']
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: [
/lib\/tests/,
/lib\/tproj\/elasticsearch/,
/lib\/tproj\/expressserver/
],
loader: "ts-loader"
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
}
]
},
mode: 'production',
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
splitChunks: {
chunks: 'all',
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
})
]
};
Thanks for all the suggestions and help guys, the problem was because the bundle.js file was not getting created, I had recently updated the version of webpack to 4
So instead of
output: {
filename: './dist/tproj/js/bundle.js'
},
Using this worked for me
output: {
path: path.resolve(__dirname, "./dist/tproj/js/"),
filename: "bundle.js",
},
Make sure if the bundle.js is changed when you run webpack

multiple errors auth0 react apollo babel webpack

I'm having a little bit of an issue when I want to implement auth0 on my project.
Whenever I solve one problem I run into another, it's always the same 3 errors :
-require is not a function
-window is not defined
-missing class properties
I've tried solving it by playing with the babelrc, changing the order of the presets
And in webpack I've added the famous as below:
"plugins: [new webpack.DefinePlugin({ 'global.GENTLY': false })],"
in webpack to no avail
I'm providing the package json/ babelrc & web pack without the modifications I cited above so you can see the "base" without the failed attempts at fixing it
Also providing the screenshots with the errors
Thanks in advance
https://imgur.com/a/8TT3v44
for the errors
this is in babelrc
{
"presets": [
"#babel/preset-react",
["#babel/preset-env", { "modules": false }],
["#babel/preset-stage-0", { "decoratorsLegacy": true }]
],
"env": {
"development": {
"compact": false
},
"jest": {
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
},
"plugins": [
"#babel/plugin-proposal-export-default-from",
[
"react-intl",
{
"messagesDir": "./extracted_messages/",
"enforceDescriptions": true
}
]
]
}
and this is the webpack
const path = require('path')
const CopyPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const webpack = require('webpack')
const distDir = path.join(__dirname, '../dist')
const srcDir = path.join(__dirname, '../src')
module.exports = [
{
name: 'client',
target: 'web',
mode: 'development',
entry: `${srcDir}/client.jsx`,
output: {
path: distDir,
filename: 'client.js',
publicPath: '/dist/'
},
resolve: {
extensions: ['.js', '.jsx', '.json'],
alias: {
config: path.join(__dirname, '../config'),
utils: path.join(__dirname, '../src/utils'),
toolbox: path.join(__dirname, '../src/components/toolbox')
}
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules\/)/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(jpe?g|png|gif)$/,
loader: 'file-loader',
query: { name: 'assets/images/[name].[ext]' }
},
{
test: /\.(woff2?|eot|ttf|otf)$/,
loader: 'file-loader',
query: { name: 'assets/fonts/[name].[ext]' }
}
]
},
plugins: [
new webpack.DefinePlugin({ 'global.GENTLY': false }),
new MiniCssExtractPlugin({
filename: 'styles.css'
}),
new CopyPlugin([{ from: `${srcDir}/favicon.ico`, to: distDir }])]
},
{
name: 'server',
target: 'node',
mode: 'development',
entry: `${srcDir}/server.jsx`,
output: {
path: distDir,
filename: 'server.js',
libraryTarget: 'commonjs2',
publicPath: '/dist/'
},
resolve: {
extensions: ['.js', '.jsx', '.json'],
alias: {
config: path.join(__dirname, '../config'),
utils: path.join(__dirname, '../src/utils'),
toolbox: path.join(__dirname, '../src/components/toolbox'),
inherits: 'inherits/inherits_browser.js',
superagent: 'superagent/lib/client',
emitter: 'component-emitter',
}
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules\/)/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
{
loader: 'isomorphic-style-loader'
},
{
loader: 'css-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(jpe?g|png|gif)$/,
loader: 'file-loader',
query: { name: 'assets/images/[name].[ext]' }
},
{
test: /\.(woff2?|eot|ttf|otf)$/,
loader: 'file-loader',
query: { name: 'assets/fonts/[name].[ext]' }
}
]
},
plugins: [
new webpack.DefinePlugin({ 'global.GENTLY': false }),
new CopyPlugin([{ from: `${srcDir}/favicon.ico`, to: distDir }])]
}
]
I ran into this problem while writing for our blog. Our suggested fix is this;
function whatYouRunOnPageLoad() {
if (typeof window !== undefined) {
auth0.parseHash(... etc ...)
}
}
parseHash requires window, which does not exist as part of your render steps. Auth0.js cannot run from serverside, which is what is "accidentally" happening when you try to render it the way you are.
Window error solved by doing:
if(global.window){...}
and later on by just not calling the function I was using at inappropriate times.
Require is not a function solved with:
[new webpack.DefinePlugin({ 'global.GENTLY': false })]
in the webpack config at plugins (dev AND prod, idk why) + importing it with require and not import.
Webpack module error solved by changing the order of the presets in bablerc.

ReactJS with Webpack Setup - App Shows A Blank Page

I had a different thread here: React Build Tool and Dev Server
to setup React with Webpack. Seems like it is working but I have an issue with having the html page show the code from entry point app.js . I can see the code is in bundle.js. If I modify anything in app.js till the render method e.g enter a typo or something I see an error on console but nothing happens with the render() method. Not matter what I do there is no error and nothing shows but a blank page.
app.js
import React from 'react';
import ReactDOM from 'react-dom';
export default class App extends React.Component {
render() {
return (
ReactDOM.render(<h1>Render me!</h1>,
document.getElementById('app'))
);
}
}
Index.html
<!DOCTYPE html>
<html>
<head>
<!-- Bootstrap, latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src='bundle.js'></script>
</body>
</html>
So if I view page source it just shows just
and not the expected Render me!
And just in case below is my webpack.config
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
bundle: './src/app.js'
},
output: {
path: path.join(__dirname, '/dist'),
filename: 'bundle.js'
},
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}]
},
resolve: {
extensions: ['*', '.js', '.jsx']
}
};
Also this is from my package.json. I believe my bundle.js is being served from memory right now.
"scripts": {
"start": "webpack-dev-server --port 3000 --hot --inline",
"build": "webpack --progress --colors"
}
I run npm start to compile and start the server. I was expecting npm build will build to dist folder but it doesn't . For now I just want this working one way or the other so I can start coding.
And .babelrc
{
"presets":[
"es2017", "react"
]
}
You are using WebPack 3.x?
Try this config:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const autoprefixer = require('autoprefixer');
const staticSourcePath = path.join(__dirname, 'static');
const sourcePath = path.join(__dirname);
const buildPath = path.join(__dirname, 'dist');
module.exports = {
devtool: 'source-map',
devServer: {
historyApiFallback: true,
contentBase: './'
},
entry: {
"index" :path.resolve(sourcePath, 'index.js')
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].[chunkhash].js',
publicPath: '/'
},
resolve: {
extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
modules: [
sourcePath,
path.resolve(__dirname, 'node_modules')
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.[chunkhash].js',
minChunks: Infinity
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer({
browsers: [
'last 3 version',
'ie >= 10'
]
})
],
context: staticSourcePath
}
}),
new webpack.HashedModuleIdsPlugin(),
new HtmlWebpackPlugin({
template: path.join(__dirname, 'index.html'),
path: buildPath,
excludeChunks: ['base'],
filename: 'index.html',
minify: {
collapseWhitespace: true,
collapseInlineTagWhitespace: true,
removeComments: true,
removeRedundantAttributes: true
}
}),
new PreloadWebpackPlugin({
rel: 'preload',
as: 'script',
include: 'all',
fileBlacklist: [/\.(css|map)$/, /base?.+/]
}),
new webpack.NoEmitOnErrorsPlugin()
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react'],
}
},
include: sourcePath
},
{
test: /\.css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{ loader: 'css-loader', options: { minimize: true } },
'postcss-loader',
'sass-loader'
]
})
},
{
test: /\.(eot?.+|svg?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
use: 'file-loader?name=assets/[name]-[hash].[ext]'
},
{
test: /\.(png|gif|jpg|svg)$/,
use: [
'url-loader?limit=20480&name=assets/[name]-[hash].[ext]'
],
include: staticSourcePath
}
]
}
};

How to handle static assets with webpack server side?

I'm trying to create an universal react app (using webpack both on server and on the client) and struggle with images import. I want to write this :
import someImage from './someImage.png'
const SomeImage = () => <img src={someImage}/>
Here's my webpack config file:
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: [
'webpack-dev-server/client?http://127.0.0.1:8080/',
'webpack/hot/only-dev-server',
'./client',
'babel-polyfill'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
resolve: {
modulesDirectories: ['node_modules', 'shared'],
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['babel']
},
{
test: /\.css/,
exclude: /node_modules/,
loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]')
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?emitFile=false',
]
}
]
},
plugins: [
new ExtractTextPlugin('styles.css', { allChunks: true }),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
devtool: 'inline-source-map',
devServer: {
hot: true,
proxy: {
'*': 'http://127.0.0.1:' + (process.env.PORT || 3000)
},
host: '127.0.0.1'
}
};
Obviously it's not working server side because node try to read the content of the ./someImage.png file, resulting in an error.
How can I handle this ? I know there are packages such as webpack-isomorphic-tools or universal-webpack or even the file-loader package that can emit or not the file, but I don't understand of to use it in my universal app.
I'm using file-loader with emitFile: false to exclude assets from bundling on server side. Works as expected.
const imageRules = (emit = true) => ({
test: /\.(png|svg|jpeg|jpg|gif|ico)$/,
type: "asset",
generator: {
emit: emit,
},
});
Then use it in webpack client config:
module: {
rules: [imageRules()],
},
And in server config
module: {
rules: [imageRules(false)],
},

Webpack 2 beta + history API fallback not working

Today, after removing my node_modules and reinstalling them using npm install, my project doesn't seem to work.
Here's my webpack config
const webpack = require('webpack');
const path = require('path');
const srcPath = path.join(__dirname, './client');
const nodeEnv = process.env.NODE_ENV || 'development';
const isProd = nodeEnv === 'production';
module.exports = {
devtool: isProd ? 'hidden-source-map' : 'cheap-module-eval-source-map',
context: path.join(__dirname, './client'),
entry: {
js: './index.js',
vendor: ['react']
},
output: {
path: path.join(__dirname, './static'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.html$/,
loader: 'file',
query: {
name: '[name].[ext]'
}
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loaders: ['babel-loader']
},
{
test: /\.(png|jpg|gif|otf|eot|svg|ttf|woff|woff2)/,
loader: 'url-loader'
},
{
test: /\.(txt|json)/,
loader: 'raw-loader'
}
],
},
resolve: {
extensions: ['', '.js', '.jsx'],
modules: [
path.resolve('./client'),
'node_modules'
],
alias: {
stores: `${srcPath}/stores/`,
components: `${srcPath}/components/`,
services: `${srcPath}/services`,
models: `${srcPath}/models`,
constants: `${srcPath}/constants`,
sources: `${srcPath}/sources`,
images: `${srcPath}/assets/images`,
appConstants: isProd ? `${srcPath}/constants/_prod` : `${srcPath}/constants/_dev`
}
},
plugins: [
new webpack.IgnorePlugin(/regenerator|nodent|js\-beautify/, /ajv/),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity,
filename: 'vendor.bundle.js'
}),
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: isProd
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: !isProd
},
output: {
comments: !isProd
},
sourceMap: !isProd
}),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify(nodeEnv) }
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.OccurrenceOrderPlugin()
],
devServer: {
contentBase: './client',
hot: true,
port: 3000,
historyApiFallback: true
}
};
My "client" folder with index.html and the rest of my code are in the same folder as webpack config.
Webpack does succesfully build, but going to localhost:3000, I get error message: "Cannot GET /"
Going to localhost:3000/client/index.html does serve my index.html, but my built files inserted using
<script src="./vendor.bundle.js"></script>
<script src="./bundle.js"></script>
doesn't load (GET to "http://localhost:3000/client/bundle.js" results in 404)
Anyone knows what's going on? I can't fix this issue, and I think I've tried everything, from changing path, publicPath to changing contentBase and moving my static files to different folder.
It's very strange, since this issue appeared only after reinstalling my project dependencies.
Every bit of help is much appreciated. Thanks.
There was an issue in webpack-dev-server#2.1.0-beta.3, which caused the contentBase option to be ignored. Could you try upgrading to 2.1.0-beta.4? It was just released.

Categories