Webpack prod vs dev - node.js

In my webpack configuration, I've tried to make separate configuration to my prod and dev enviroments. I'm trying to achieve to different JS files for each task. Meaning, when I build it, I need my code to go to the prod environment with a specific name "lib.js" and when I run my Dev environment, I want the compiled files to go to the "dist" folder.
This is my webpack.config.js file:
const webpack = require('webpack')
const ExtractTextPlugin = require("extract-text-webpack-plugin")
let path = require('path');
let config = {
entry: [
'./src/index.js'
],
module: {
rules: [{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
'react-hot-loader',
'babel-loader'
]
},
{
test: /\.(css)$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
},
{
test: /\.less$/,
use:ExtractTextPlugin.extract({
use: 'less-loader'
})
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader',
},
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
}
],
},
resolve: {
extensions: ['*', '.js', '.jsx', '.css'],
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}
})
],
devServer: {
contentBase: './dist',
historyApiFallback: true
},
devtool : "cheap-module-source-map",
}
if (process.env.NODE_ENV === 'production') {
config.output= {
path: path.join(__dirname, '/build/'),
filename: 'lib.js',
library: ['MyLibrary'],
libraryTarget: 'umd'
};
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({ sourceMap: true }),
new ExtractTextPlugin({
filename: 'bundle.css',
disable: false,
allChunks: true
}),
new webpack.optimize.AggressiveMergingPlugin({
minSizeReduce: 1,
moveToParents: true
})
)
} else {
config.output= {
path: path.join(__dirname, '/dist/'),
filename: 'bundle.js',
library: ['MyLibrary'],
libraryTarget: 'umd',
publicPath: '/dist/'
};
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({ sourceMap: true }),
new ExtractTextPlugin({ disable: true })
)
}
module.exports = config
and these are my scripts:
"scripts": {
"dev": "webpack-dev-server -d --env.platform=default --progress --hot",
"build": "set NODE_ENV=production && webpack -p --progress --hot"
}
What actually happens is that only when I build, the files go to the dist folder, even though I've set the NODE_ENV param to "production".
Would be glad for help.
Thanks!

It could be the trailing space that you have after NODE_ENV=production, which probably sets NODE_ENV to production with a space after which won't match in your webpack config. Try to change it in the package.json like this:
"build": "set NODE_ENV=production&& webpack -p --progress --hot"
This is mentioned in the comment by #daw on this SO answer.

Related

Undefined .env variables when webpack goes into production mode

I'm using the dot-env NPM package in order to pass simple variables to my webpack/express application.
When I run in PRODUCTION mode for webpack, all my variables from .env become undefined.
I'm building up a development and production webpack config files and currently have the following setup.
Any advise on the mistakes I'm making and why my .env variables are being dropped would be greatly appreciated.
package.json (Scripts)
"buildDev": "rm -rf dist && webpack --mode development --config webpack.server.config.js && webpack --mode development --config webpack.dev.config.js",
"buildProd": "rm -rf dist && webpack --mode production --config webpack.server.config.js && webpack --mode production --config webpack.prod.config.js",
webpack.dev
const path = require("path");
const webpack = require("webpack");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const paths = require("./config/paths");
const isDevelopment = false;
const Dotenv = require('dotenv-webpack');
require('dotenv').config()
module.exports = {
entry: {
main: [
"webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000",
paths.appIndexJs,
],
},
output: {
path: path.join(__dirname, "dist"),
publicPath: "/",
filename: "[name].js",
},
devServer: {
historyApiFallback: true,
},
mode: "production",
target: "web",
devtool: "#source-map",
module: {
rules: [
{
enforce: "pre",
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
emitWarning: true,
failOnError: false,
failOnWarning: false,
},
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: path.resolve(paths.appSrc),
loader: "babel-loader",
},
{
// Loads the javacript into html template provided.
// Entry point is set below in HtmlWebPackPlugin in Plugins
test: /\.html$/,
include: path.resolve(paths.appSrc),
use: [
{
loader: "html-loader",
},
],
},
{
test: /\.css$/,
include: path.resolve(paths.appSrc),
use: ["style-loader", "css-loader"],
},
{
test: /\.css$/,
include: /node_modules/,
use: ["style-loader", "css-loader"],
},
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"],
},
{
test: /\.(png|svg|jpg|gif|eot|woff|woff2|ttf)$/,
use: ["file-loader"],
},
],
},
resolve: {
extensions: [".js", ".jsx"],
},
plugins: [
new HtmlWebPackPlugin({
favicon: "./src/assets/img/favicons/favicon.ico",
template: "./src/html/index.html",
filename: "./index.html",
excludeChunks: ["server"],
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new Dotenv()
],
};
webpack.prod
const path = require("path");
const webpack = require("webpack");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const paths = require("./config/paths");
const isDevelopment = false;
const Dotenv = require('dotenv-webpack');
require('dotenv').config()
module.exports = {
entry: {
main: [
"webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000",
paths.appIndexJs,
],
},
output: {
path: path.join(__dirname, "dist"),
publicPath: "/",
filename: "[name].js",
},
devServer: {
historyApiFallback: true,
},
mode: "production",
target: "web",
devtool: "#source-map",
module: {
rules: [
{
enforce: "pre",
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
emitWarning: true,
failOnError: false,
failOnWarning: false,
},
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: path.resolve(paths.appSrc),
loader: "babel-loader",
},
{
// Loads the javacript into html template provided.
// Entry point is set below in HtmlWebPackPlugin in Plugins
test: /\.html$/,
include: path.resolve(paths.appSrc),
use: [
{
loader: "html-loader",
},
],
},
{
test: /\.css$/,
include: path.resolve(paths.appSrc),
use: ["style-loader", "css-loader"],
},
{
test: /\.css$/,
include: /node_modules/,
use: ["style-loader", "css-loader"],
},
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"],
},
/*{
test: /\.scss$/,
use: [
{ loader: 'css-loader', options: { url: false, sourceMap: true } },
{ loader: 'sass-loader', options: { sourceMap: true }
},
]
},*/
/*{
test: /\.css$/,
include: path.resolve(paths.appSrc),
use: ["style-loader", "css-loader"],
},
{
test: /\.sass$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { url: false, sourceMap: true } },
{ loader: 'sass-loader', options: { sourceMap: true } },
]
},
{
test: /\.css$/,
include: /node_modules/,
loader: [
isDevelopment ? "style-loader" : MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
modules: true,
sourceMap: isDevelopment,
},
},
],
},
{
test: /\.(scss)$/,
use: [
MiniCssExtractPlugin.loader, { loader: 'css-loader',
options: { url: false, sourceMap:
true } }, { loader: 'sass-loader', options: { sourceMap: true } },
]
},*/
{
test: /\.(png|svg|jpg|gif|eot|woff|woff2|ttf)$/,
//include: path.resolve(paths.appSrc),
use: ["file-loader"],
},
],
},
resolve: {
extensions: [".js", ".jsx"],
},
plugins: [
new webpack.DefinePlugin({
'process.env': { 'NODE_ENV': JSON.stringify('production') }
}),
new HtmlWebPackPlugin({
favicon: "./src/assets/img/favicons/favicon.ico",
template: "./src/html/index.html",
filename: "./index.html",
excludeChunks: ["server"],
}),
new webpack.NoEmitOnErrorsPlugin(),
new Dotenv()
],
};
webpack.server
const path = require("path");
const webpack = require("webpack");
const nodeExternals = require("webpack-node-externals");
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = (env, argv) => {
const SERVER_PATH =
argv.mode === "production" ? "./src/server/server-prod.js" : "./src/server/server-dev.js";
return {
entry: {
server: SERVER_PATH,
},
output: {
path: path.join(__dirname, "dist"),
publicPath: "/",
filename: "[name].js",
},
mode: argv.mode,
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()], // Need this to avoid error when working with Express
devServer: {
historyApiFallback: true,
},
module: {
rules: [
{
// Transpiles ES6-8 into ES5
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
}
],
},
};
};
If you look at yow webpack.prod in its plugins section you have it like.
new webpack.DefinePlugin({
'process.env': { 'NODE_ENV': JSON.stringify('production') }
So basically you is setting process.env to be equals to What Eva is there
solution
first you need to install two modules
dotenv-expand
dotenv
$ npm i -D dotenv-expand dotenv
Next
create a new file called env.js, I mean the name is up to you. Place the file same place where yow webpacks are
env.js
'use strict';
const fs = require('fs');
const path = require('path');
const {NODE_ENV} = process.env.NODE_ENV;
const dotenvFile = `.env.${NODE_ENV}`;
require('dotenv-expand')(
require('dotenv').config({
path: dotenvFile,
}));
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '')
.split(path.delimiter)
.filter(folder => folder && !path.isAbsolute(folder))
.map(folder => path.resolve(appDirectory, folder))
.join(path.delimiter);
// set your own prefix
const PREFIX = /^ENETO_/i;
function getEnvironment() {
const raw = Object.keys(process.env)
.filter(key => PREFIX.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
NODE_ENV: process.env.NODE_ENV || 'development',
PORT: process.env.PORT||3000,
}
);
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
console.log("stringified", stringified);
return { raw, stringified };
}
module.exports = getEnvironment();
NOTE
Make sure to add a prefix so all of them shuld start with a PREFIX
you can set your own prefix
now on each one of yow webpacks add it;
webpack.server.js
/**
webpack server
*/
"use strict";
const path = require("path");
const nodeExternals = require("webpack-node-externals");
const webpack = require("webpack");
/**
* HERE IS IMPORTED ALL THE WAY TO THE BOTTOM YOU'LL SEE IT
*/
const vars = require("./env");
const { NODE_ENV } = process.env;
const entry = [path.join(__dirname, NODE_ENV === "production" ? `../src/prod.ts` : `../src/dev.ts`)];
module.exports = {
target: "node",
name: "server",
externals: [nodeExternals()],
entry: [
require.resolve("#babel/register"),
require.resolve("core-js/proposals"),
require.resolve("core-js"),
require.resolve("#babel/runtime-corejs3/regenerator"),
require.resolve("es6-promise/auto"),
...entry,
],
devtool: false,
mode: process.env.NODE_ENV,
output: {
filename: "[name]-bundle.js",
chunkFilename: "[name].chunk.js",
path: path.resolve(__dirname, "../bundle"),
publicPath: "/",
libraryTarget: "commonjs2",
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
},
],
},
{
test: /\.(js|mjs)$/,
exclude: /#babel(?:\/|\\{1,2})runtime/,
loader: require.resolve("babel-loader"),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [[require.resolve("#babel/preset-env")]],
cacheDirectory: true,
cacheCompression: false,
sourceMaps: false,
inputSourceMap: false,
},
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: "file-loader",
},
],
},
],
},
plugins: [new webpack.DefinePlugin(vars.stringified)],
};
Do the same with yow client and thats it :3
do not need third part deps.
just use env like this:
--node-env=
// in package.json
"build": "webpack --node-env=production --config build/webpack.config.js"
or
module.exports = (env, argv) => {
const isDevelopment = argv.mode !== 'production';
return {
// Config...
}
}
see:
--node-env
argv

Error: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

I'm getting this weird error when I'm trying to do a "npm run dev". First, I cloned a repo, then changed into that project folder where I did a "npm install".
After it was done, I tried the "npm run dev", but it gave me a long error:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration[0].mode should be one of these:
"development" | "production" | "none"
-> Enable production optimizations or development hints.
- configuration[1].mode should be one of these:
"development" | "production" | "none"
-> Enable production optimizations or development hints.
My webpack.config.js file:
const path = require('path');
var nodeExternals = require('webpack-node-externals');
const serverConfig = {
mode: process.env.NODE_ENV || 'development',
entry: './src/server/server.ts',
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
configFile: 'tsconfig.server.json'
}
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'server.js',
path: path.resolve(__dirname, 'dist')
},
target: 'node',
node: {
__dirname: false
},
externals: [nodeExternals()]
};
const clientConfig = {
mode: process.env.NODE_ENV || 'development',
entry: './src/client/index.tsx',
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
configFile: 'tsconfig.client.json'
}
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
]
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js', '.css', '.scss']
},
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'public/js')
}
};
module.exports = [serverConfig, clientConfig];

How to use Development Version of Reactjs with Webpack 4

This is my current webpack configuration. Its been a while since I've had to do this, and the last time I did it webpack 2 was just coming out. At that point there was a plugin that would allow me to define my output. Now that plugin is no longer valid.
What I need to do is use the development version of ReactJS but my builds keep building with the production version. So error handling is next to impossible since react removes a bulk of the errors in a production build.
const fs = require('fs');
const os = require('os');
const path = require('path');
const webpack = require('webpack');
const files = fs.readdirSync('./src/scripts/').filter(function (file) {
return path.extname(file) === '.js';
});
const entries = files.reduce(function (obj, file, index) {
const key = path.basename(file, '.js');
obj[key] = [
'./src/scripts/' + key
];
return obj;
}, {});
entries.hotreload = 'react-hot-loader/patch';
console.log(argv.mode);
module.exports = {
mode: 'development',
entry: entries,
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist/scripts',
publicPath: '/',
filename: '[name].js'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: './dist/scripts',
hot: true
}
};
This is also how I start webpack webpack-dev-server --config ./webpack.config.js --mode development which doesn't seem to do me any good.
Well, I create a script to run the webpack server. This is how I start the dev server npm start.
Here is my scripts:
"scripts": {
"dev": "webpack --mode development",
"start": "webpack-dev-server",
"build": "cross-env NODE_ENV=production webpack-dev-server --client-log-level none --color --compress"
},
And here my webpack.config.js:
const modoDev = process.env.NODE_ENV != "production";
const webpack = require('webpack');
const ExtractTextPlugin = require('mini-css-extract-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const path = require('path');
module.exports = {
mode: modoDev ? 'development' : 'production',
entry: './src/index.jsx',
output: {
path: __dirname + '/public',
filename: './app.js',
publicPath: '/'
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true
}),
new OptimizeCssAssetsPlugin({})
]
},
devServer: {
host: '0.0.0.0',
port: 8080,
contentBase: './public',
historyApiFallback: {
index: "/"
},
},
resolve: {
extensions: ['*', '.js', '.jsx'],
alias: {
modules: path.resolve(__dirname + '/node_modules/')
}
},
plugins: [new ExtractTextPlugin({
filename: 'app.css'
}), new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})],
module: {
rules: [{
test: /.js[x]?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [ExtractTextPlugin.loader, 'css-loader', 'sass-loader']
}, {
test: /\.woff|.woff2|.ttf|.eot|.svg|.png|.jpg*.*$/,
use: ['file-loader']
},
],
}
};

React + Webpack: process.env is EMPTY after run build

A common problem but as usual, every solution found on this website, not fit my case.
I've create a .env.production file with specific constant.
In my package.json I have:
"build": "NODE_ENV=production webpack --config webpack.config.js --colors",
I run the build with the classic: npm run build
This is my webpack.config
const webpack = require('webpack');
const path = require('path');
var config = {
context: __dirname + '/src',
entry: {
javascript: "./index.js",
},
output: {
// path:path.join(__dirname, './dist'),
path: path.join(__dirname,'../static/js/'),
filename: 'bundle.js',
},
devServer: {
inline: true,
port: 8080
},
resolveLoader: {
modules: [path.join(__dirname, 'node_modules')]
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react']
}
},
{
test: /\.css$/,
loader: 'style-loader'
},
{
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
{
test: /\.svg$/,
use: [
{
loader: "babel-loader"
},
{
loader: "react-svg-loader",
options: {
jsx: true // true outputs JSX tags
}
}
]
}
]
},
}
module.exports = config;
As you can see, Im not overriding ENV in webpack config using the webpack.DefinePlugin plugin.
So why my process.env is EMPTY?
When I start the app with npm start, the process.env is normally filled and process.env.NODE_ENV is set to development.
Thank you for any help!

webpack using with nodejs

I am new in reactjs. I am just start learning reactjs. I have problem using webpack in nodejs. I want to create node server which will run the webpack file. I have webpack file:
const {resolve} = require('path');
const webpack = require('webpack');
const validate = require('webpack-validator');
const {getIfUtils, removeEmpty} = require('webpack-config-utils');
module.exports = env => {
const {ifProd, ifNotProd} = getIfUtils(env)
return validate({
entry: './index.js',
context: __dirname,
output: {
path: resolve(__dirname, './build'),
filename: 'bundle.js',
publicPath: '/build/',
pathinfo: ifNotProd(),
},
devtool: ifProd('source-map', 'eval'),
devServer: {
port: 8080,
historyApiFallback: true
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
{test: /\.css$/, loader: 'style-loader!css-loader'},
{test: /(\.eot|\.woff2|\.woff|\.ttf|\.svg)/, loader: 'file-loader'},
],
},
plugins: removeEmpty([
ifProd(new webpack.optimize.DedupePlugin()),
ifProd(new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false,
quiet: true,
})),
ifProd(new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"',
},
})),
ifProd(new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
screw_ie8: true, // eslint-disable-line
warnings: false,
},
})),
])
});
};
How can i use this configuration with nodejs. please help
First of all your webpack configuration will not run on webpack 2+, because webpack-validator is deprecated, so I have removed it. I would recommend you to install npm install webpack-dev-server -g globally and use it as a server in your react development. This is how you can modify your configuration to use it (webpack.config.js):
const path = require("path");
const webpack = require('webpack');
const {getIfUtils, removeEmpty} = require('webpack-config-utils');
module.exports = env => {
const {ifProd, ifNotProd} = getIfUtils(env)
return {
entry: [
"webpack-dev-server/client?http://localhost:3003",
"webpack/hot/only-dev-server",
"react-hot-loader/patch"
],
context: __dirname,
output: {
path: path.join(__dirname, './build'),
filename: 'bundle.js',
publicPath: '/build/',
pathinfo: ifNotProd(),
},
devtool: ifProd('source-map', 'eval'),
devServer: {
contentBase: path.join(__dirname, "src"),
// enable HMR
hot: true,
// embed the webpack-dev-server runtime into the bundle
inline: true,
// serve index.html in place of 404 responses to allow HTML5 history
historyApiFallback: true,
port: 3003
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
{test: /\.css$/, loader: 'style-loader!css-loader'},
{test: /(\.eot|\.woff2|\.woff|\.ttf|\.svg)/, loader: 'file-loader'},
],
},
plugins: removeEmpty([
//...
// same as before
//...
])
};
};
package.json :
{
...
"dependencies": {},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"react-hot-loader": "^3.1.1",
"webpack": "^3.8.1",
"webpack-config-utils": "^2.3.0",
"webpack-dev-server": "^2.9.4",
}
}
in the same folder where webpack.config.js is make one file webpack.development.js, that will just set enviorment:
var config = require('./webpack.config.js')
module.exports = config("development"); // can be "production" or "development"
Files structure:
root
build
bundle.js
src
index.html
index.js
package.json
webpack.config.js
webpack.development.js
At the end just run it:
webpack-dev-server --config webpack.development.js --progress -p --hot -w
--hot - will run server,
-w - watch files
My suggestion:
package.json scripts (install webpack (-g and –save-dev), nodemon (-g and –save-dev) and concurrently (–save-dev))
"scripts": {
"webpack-watch-client": "webpack -w",
"server": "nodemon server",
"dev": "concurrently --kill-others \"npm run webpack-watch-client\" \"npm run server\""
}
webpack.config.js example
'use strict'
const path = require('path');
const PATHS = {
app: path.join(__dirname, 'src'),
public: path.join(__dirname, 'public')
};
module.exports = {
entry: {
app: PATHS.app,
},
output: {
path: PATHS.public,
filename: 'js/bundle.js'
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['react', 'es2015']
}
}
]
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' }
]
},
{
test: /\.(woff|woff2|eot|ttf)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'assets/fonts/'
}
}
]
},
{
test: /\.(png|jpg|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'assets/img/'
}
}
]
}
]
},
plugins: [
// plugins
]
};
Node server start point is ./server.js
React client start point is ./src/index.js
Output path ./public contain index.html with lines:
<div id="root"></div>
<script type="text/javascript" src="/js/bundle.js" charset="utf-8"></script>
Output path for bundle.js is ./public/js
Output path for fonts is ./public/assets/fonts
Output path for images is ./public/assets/img
Start: npm run dev (listening port is defined in server.js)
etc.
I don't know if this would help, but i think that you want do the other way round:
Create your configuration un Webpack.config file (Webpack).
Your webpack file lauch the Node server (Express).
Your server return your font-end file (React).
You can learn some info about webpack in this post.
Try this. Save this code in webpackConfig.js
var webpack = require('webpack')
var config = require('./your_config')
var compiler = webpack(config)
compiler.run(function(err, stats){
console.log(err, stats)
})
run with "node webpackConfig.js"

Resources