Accessing environment variables via webpack - reactjs

I have developed a react webpack application and I have implemented as follows to access environment variables.
webpack.config.js
const webpack = require('webpack');
var config = {
entry: './main.js',
output: {
filename: 'bundle.js',
},
devServer: {
inline: true,
disableHostCheck: true,
host: '0.0.0.0',
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
ENV_VAR: JSON.stringify(process.env.ENV_VAR)
}
})
]
};
module.exports = config;
and in my config.js I have implemented as follows to maintain my config structure.
export default () => {
return {
"configFromEnvVar": {
"url": process.env.ENV_VAR || "http://url:8080"
}
}
};
I want to know if there is a better way to do this without having to use process.env in multiple locations. Any documentation or advice is greatly appreciated.
Thanks alot

Related

Webpack production request https

I have a problem. I am using axios to make a request to a http target, but when building the code, the bundle request to a https as show in the picture.
Maybe I need to do some configuration on my webpack config.
correct target: http://ip-api.com/json
wrong target: https://ip-api.com/json
webpack.prod.config.js
const common = require('./webpack.common.config')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = merge(common, {
mode: 'production',
module: {
rules: [
{
test: /\.ts(x?)$/,
loader: 'ts-loader',
exclude: /node_module/
},
{
test: /\.scss$/,
use: [{
loader: MiniCssExtractPlugin.loader
}, {
loader: 'css-loader',
options: {
modules: true
}
}, {
loader: 'sass-loader'
}
]
}
]
},
devtool: 'cheap-module-source-map',
externals: {
axios: 'axios',
react: 'React',
'react-dom': 'ReactDOM'
},
plugins: [
new HtmlWebpackPlugin({
template: './template.prod.html'
}),
new MiniCssExtractPlugin({
filename: 'main-bundle-[hash].css'
})
// new FaviconsWebpackPlugin({
// logo: './public/static/img/favicon.png',
// inject: true
// })
]
})
I have found the solutions. I removed <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" /> from my template.prod.html and the problem was solved.

Webpack running through grunt webpack doesn't error or complete, or do anything

Trying to convert an old system off bower into npm using webpack, and grunt webpack. Just trying to use webpack to load in NPM files, not run anything else, and the rest of the grunt file finishes loading and uglifying and stuff, and runs its own node server. It gets to this point and freezes and never comes back.
Loading "grunt-webpack" plugin
Registering "/Users/***/***/***/node_modules/grunt-webpack/tasks" tasks.
Loading "webpack-dev-server.js" tasks...OK
+ webpack-dev-server
Loading "webpack.js" tasks...OK
+ webpack
Running "webpack" task
Here's my grunt code (super basic obviously)
webpack: {
options: require("./config/webpack.dev.js"),
},
Here's that dev file
const webpack = require('webpack');
const helpers = require('./helpers');
const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { BaseHrefWebpackPlugin } = require('base-href-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ConcatPlugin = require('webpack-concat-plugin');
const ngInventory = require('./ng1-vendor-index.js');
const common = require('./webpack.common.js');
const ENV = process.env.NODE_ENV = process.env.ENV = 'dev';
module.exports = merge(common(ENV), {
devtool: 'source-map',
module: {
rules: [
{
test: /\.(ts|js)$/,
loaders: ['angular-router-loader'],
},
{
test: /\.((s*)css)$/,
use: [{
loader: 'style-loader',
},{
loader: 'css-loader',
},{
loader: 'sass-loader',
}]
},
{
test: /src\/.+\.(ts|js)$/,
exclude: /(node_modules|\.spec\.ts$)/,
loader: 'istanbul-instrumenter-loader',
enforce: 'post',
options: {
esModules: true
}
}
]
},
debug: true,
devTool: 'eval',
plugins: [
new ConcatPlugin({
uglify: false,
sourceMap: true,
name: 'vendor',
outputPath: './',
fileName: '[name].[hash].js',
filesToConcat: ngInventory.vendor1
}),
new BaseHrefWebpackPlugin({ baseHref: '/'}),
new HtmlWebpackPlugin({
favicon: helpers.root('client/assets/image/favicon.png'),
template: "./client/index.html",
filename: "./client/index.html",
}),
new webpack.NoEmitOnErrorsPlugin(),
],
});
And here is the common file:
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals')
const helpers = require('./helpers');
module.exports = env => ({
entry: {
server: './server/app.js',
},
resolve: {
extensions: ['.ts', '.js']
},
output: {
path: helpers.root(`dist/${env}`),
publicPath: '/',
filename: '[name].js'
},
target: 'node',
node: {
// Need this when working with express, otherwise the build fails
__dirname: false, // if you don't put this is, __dirname
__filename: false, // and __filename return blank or /
},
externals: [nodeExternals()],
module: {
rules: [
{
// Transpiles ES6-8 into ES5
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
include: [
helpers.root('client'),
],
loader: 'html-loader'
},
{
test: /\.((s*)css)%/,
include: [
helpers.root('client/app'),
helpers.root('client/components'),
],
exclude: 'node_modules/',
loaders: ['to-string-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(woff|woff2|eot|tts)$/,
use: [{
loader: 'file-loader'
}]
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'ENV': JSON.stringify(env)
}
}),
new webpack.ContextReplacementPlugin(/\#angular(\\|\/)core(\\|\/)esm5/, path.join(__dirname, './client')),
]
});
A sample from the vendor index file:
const helper = require('./helpers');
exports.vendor1 = [
helper.root('node_modules/lodash/lodash.js'),
helper.root('node_modules/lodash-deep/lodash-deep.js'),
...
...
]
I'm just really not sure what to do, couldn't bring up any google results or stack results because theres no errors happening either. I've tried all verbose levels of logging all to no avail. What in the world am I missing?
As the documentation shows, you haven't configured any targets, like dev or prod. You've only specified options. You want
webpack: {
options: {},
dev: require("./config/webpack.dev.js"),
},
As an aside, there's no benefit to using Webpack with Grunt.

material-ui.dropzone: You may need an appropriate loader to handle this file type

Integrating material-ui-dropzone in my React app, I got this error:
./~/material-ui-dropzone/src/index.jsx Module parse failed:
...\client\node_modules\material-ui-dropzone\src\index.jsx Unexpected
token (123:26) You may need an appropriate loader to handle this file
type. SyntaxError: Unexpected token (123:26)
Here is my webpack configuration:
const Path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const Webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = (options) => { const ExtractSASS = new ExtractTextPlugin(`/styles/${options.cssFileName}`);
const webpackConfig = {
devtool: options.devtool,
entry: [
`webpack-dev-server/client?http://localhost:${+ options.port}`,
'webpack/hot/dev-server',
Path.join(__dirname, '../src/app/index'),
],
output: {
path: Path.join(__dirname, '../dist'),
filename: `/scripts/${options.jsFileName}`,
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
module: {
loaders: [{
test: /.jsx?$/,
include: Path.join(__dirname, '../src/app'),
loader: 'babel',
}],
},
plugins: [
new Webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(options.isProduction ? 'production' : 'development'),
},
"global.GENTLY": false
}),
new HtmlWebpackPlugin({
template: Path.join(__dirname, '../src/index.html'),
}),
],
node: {
__dirname: true,
},
};
if (options.isProduction) {
webpackConfig.entry = [Path.join(__dirname, '../src/app/index')];
webpackConfig.plugins.push(
new Webpack.optimize.OccurenceOrderPlugin(),
new Webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false,
},
}),
ExtractSASS
);
webpackConfig.module.loaders.push({
test: /\.scss$/,
loader: ExtractSASS.extract(['css', 'sass']),
}); } else {
webpackConfig.plugins.push(
new Webpack.HotModuleReplacementPlugin()
);
webpackConfig.module.loaders.push({
test: /\.scss$/,
loaders: ['style', 'css', 'sass'],
});
webpackConfig.devServer = {
contentBase: Path.join(__dirname, '../'),
hot: true,
port: options.port,
inline: true,
progress: true,
historyApiFallback: true,
stats: 'errors-only',
}; }
return webpackConfig;
};
Babel config file is:
{
"presets": ["react", "es2015", "stage-1"]
}
It is the only library I had problems with. Any idea where might be the problem?
if you are using webapck#3.x
Try to modify your babel loader to
module: {
rules: [
{
test: /\.jsx?$/,
include: Path.join(__dirname, '../src/app'),
use: {
loader: 'babel-loader',
options: {
presets: ["react", "es2015", "stage-1"],
}
}
}
]
}
You can reference here https://webpack.js.org/loaders/babel-loader/
Noted that in your loader config, write babel-loader instead of just babel. Also make sure if you have npm install the right babel npm packages to the devDependencies, which depends on your webpack version.
If it does not solve your problem, paste your package.json file so i can get to know your webpack version.
Cheers.

Webpack 2 configuration for Tree shaking and lazy loading with System.import on React project

I am new to webpack 2 and it's lazy loading, so far I have created project without lazy loading and code splitting, but now want to split my code into chunks and use System imports with React Router. I have created React Router part according to this article
this webpack 2 config file is below.
let webpack = require('webpack');
let path = require('path');
let ExtractTextPlugin = require('extract-text-webpack-plugin');
var devFlagPlugin = new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false')),
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development'),
}
});
let extractSCSS = new ExtractTextPlugin('[name].css')
module.exports = {
context: __dirname,
entry: {
bundle: './src/app/app-client.jsx',
styles: './src/app/sass/main.scss',
vendor: [
'react', 'react-dom'
]
},
output: {
filename: '[name].js',
chunkFilename: 'chunk.[id].[chunkhash:8].js',
path: './src/build',
},
resolve: {
extensions: ['.js', '.jsx']
},
devtool: 'cheap-module-source-map',
module : {
rules : [
{
test: /\.scss$/,
loader: extractSCSS.extract(['css-loader','sass-loader'])
},
{
test: /\.jsx?$/,
exclude: [/node_modules/, /libs/],
use: {
loader: "babel-loader",
query: {
presets: ['es2015', 'react', 'stage-2' ],
plugins: [ "transform-runtime" ]
}
}
},
{
test: /\.woff2?$|\.ttf$|\.eot$|\.svg$|\.png|\.jpe?g|\.gif$/,
use: {
loader:'file-loader'
}
}
]
},
plugins: [
extractSCSS,
devFlagPlugin,
new webpack.optimize.CommonsChunkPlugin({
name: 'bundle',
children: true,
async: true,
minChunks: 2
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
children: true,
async: true,
minChunks: 2
})
]
}
but webpack creates only two files, vendor and bundle, also size of bundle hasn't reduced after I separated React and React DOM.
this is my routes.
import App from './App.jsx';
function errorLoading(err) {
console.error('Dynamic page loading failed', err);
}
function loadRoute(cb) {
return (module) => cb(null, module.default);
}
export default {
component: App,
childRoutes: [
{
path: 'stock/info/:symbol(/:tab)',
getComponent(location, cb) {
System.import('./StockPage')
.then(loadRoute(cb))
.catch(errorLoading);
}
},
{
path: '*',
getComponent(location, cb) {
System.import('./NoMatch')
.then(loadRoute(cb))
.catch(errorLoading);
}
}
]
};
my application runs, but lazy loading won't work of course, because I have no chunks of my modules within System.import.
Please help me to create right webpack config for performance of my application!
Thanks in advance and sorry if something is nonsense, since I am new to webpack.
Webpack2 switched from System.import() to import() to match the current proposed javascript feature. Which is in stage3 right now.
So you should be able to change your webpack config to include STAGE-3
{
test: /\.jsx?$/,
exclude: [/node_modules/, /libs/],
use: {
loader: "babel-loader",
query: {
presets: ['es2015', 'react', 'stage-2', 'stage-3' ],
plugins: [ "transform-runtime" ]
}
}
},
Or the dynamic-import plugin
{
test: /\.jsx?$/,
exclude: [/node_modules/, /libs/],
use: {
loader: "babel-loader",
query: {
presets: ['es2015', 'react', 'stage-2' ],
plugins: [ "transform-runtime", "syntax-dynamic-import"]
}
}
},
Then change your routes
export default {
component: App,
childRoutes: [
{
path: 'stock/info/:symbol(/:tab)',
getComponent(location, cb) {
import('./StockPage')
.then(loadRoute(cb))
.catch(errorLoading);
}
},
{
path: '*',
getComponent(location, cb) {
import('./NoMatch')
.then(loadRoute(cb))
.catch(errorLoading);
}
}
]
};
See the webpack2 help page here for full docs on using import for code splitting and lazy loading.
https://webpack.js.org/guides/migrating/#code-splitting-with-es2015
https://github.com/tc39/proposal-dynamic-import
To enable Webpack2 tree shaking which only requires making one change to your babel setup.
presets: ['es2015', 'react', 'stage-2' ],
becomes
presets: [['es2015', { modules: false }], 'react', 'stage-2' ],
This is the article that I found out about treeshaking from: https://medium.freecodecamp.com/tree-shaking-es6-modules-in-webpack-2-1add6672f31b#.lv3ldgfhs

Configure react webpack for deploy

need a little help.
We had tried to deploy a react project, but we are unable to configure it.
We use: es6, webpack, redux, react, babel.
this is webpack base:
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
export default {
entry: './app/app.js',
output: {
path: './app/App/dist',
filename: '/bundle.js',
},
module: {
loaders: [
{
test: /\.json$/,
loader: 'json',
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css!sass'),
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('css!sass'),
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.svg$/,
loader: 'babel?presets[]=es2015,presets[]=react!svg-react',
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './app/App/index.html',
}),
new ExtractTextPlugin('/app/App/css/default.css', {
allChunks: true,
}),
],
};
webpack dev:
import webpack from 'webpack';
import baseConfig from './webpack.config.base';
const config = {
...baseConfig,
debug: true,
devtool: 'cheap-module-eval-source-map',
plugins: [
...baseConfig.plugins,
new webpack.HotModuleReplacementPlugin(),
],
devServer: {
colors: true,
historyApiFallback: true,
inline: true,
hot: true,
},
};
export default config;
webpack prod:
import webpack from 'webpack';
import baseConfig from './webpack.config.base';
const config = {
...baseConfig,
plugins: [
...baseConfig.plugins,
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compressor: {
screw_ie8: true,
warnings: false,
},
}),
],
};
export default config;
This is our actual webpack, we are trying to deploy the project with it, but does not work.
Does anyone have an idea how to configure it?
So, it's a server problem probably. You need a HTTP server in order to server the static files (your app basically). I recommend the Ngxin, very easy to configure and use.
After install nginx, delete the /etc/nginx/sites-enable/default file and create a new one (you can use whatever name you want here). Here's the config I use:
server {
listen 80;
listen [::]:80;
server_name example.com;
location / {
root /var/html/myProject/;
try_files $uri /index.html;
}
}
after that, restart nginx and should be ready to go.
for webpack, I have a simpler config that works well:
const path = require("path");
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const isProd = process.env.NODE_ENV && process.env.NODE_ENV.toLowerCase() == 'production';
const plugins = [
new ExtractTextPlugin(isProd ? 'bundle.[hash].css' : 'bundle.css', { allChunks: true }),
new HtmlWebpackPlugin({
template: 'index.html',
inject: 'body',
filename: 'index.html'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
})
];
const prodPlugins = [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
];
module.exports = {
devtool: isProd ? 'cheap-module-source-map' : 'eval',
entry: [
'./src/index.jsx'
],
output: {
path: isProd ? path.join(__dirname, 'dist') : __dirname,
publicPath: '/',
filename: isProd ? 'bundle.[hash].js' : 'bundle.js'
},
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{
test: /\.(scss|css|sass)$/,
loader: ExtractTextPlugin.extract('css!sass')
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url'
},
{
test: /\.html$/,
loader: 'html'
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
},
plugins: isProd ? prodPlugins.concat(plugins) : plugins
};
A few points:
I'm using SASS
Check the path's before run anything
To compile for production, just run NODE_ENV=production webpack -p
I'm using a few plugins for Uglify JS and compress files.
I think that's it! Cheers!
sure I think the fastest way to solve your problem is to click on this link:
React starter kit
and select any starters that matches your technologies!
I think you are looking for this one : react-boilerplate

Resources