Setting Node Enviorments for my GULP / WEPACK workflow - javascript

i am trying to use NODE.env to determine weather i want to minify my JS with webpack or not, it does work when i set the env in the js manually but i thought i could also integrate it into my default and build task. somehow it doesn't work.
package.json
.
.
.
"scripts": {
"dev": "gulp",
"build": "gulp build"
}
Gulpfile.js :
'use strict';
const gulp = require('gulp'),
// cleanCSS = require('gulp-clean-css'),
webpack = require('webpack-stream'),
pkg = require('./package.json'),
$ = require('gulp-load-plugins')({
pattern: ['*'],
scope: ['devDependencies']
}),
onError = (err) => {
$.notify.onError({
title: 'Gulp',
subtitle: 'Failure!',
message: '\n' + '\n' + 'Error: <%= error.message %>',
sound: 'Frog'
})(err);
};
/**
* Static Server + watching scss/html files
*/
gulp.task('serve', ['scss', 'webpack'], () => {
$.browserSync.init({
server: pkg.paths.src.base
});
gulp.watch(pkg.paths.src.scss + pkg.vars.scssPattern, ['scss']);
gulp.watch(pkg.paths.src.js + pkg.vars.jsPattern, ['webpack']);
gulp.watch('src/*.html').on('change', $.browserSync.reload);
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('scss', () => {
return gulp.src(pkg.paths.src.scss + pkg.vars.scssName)
.pipe($.newer(pkg.paths.src.assets + pkg.vars.siteCssName))
.pipe($.plumber({ errorHandler: onError }))
.pipe($.sourcemaps.init())
.pipe($.sass.sync())
.pipe($.sourcemaps.write())
.pipe($.autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe($.rename({suffix: '.min'}))
.pipe(gulp.dest(pkg.paths.src.assets))
.pipe($.notify({
title: 'Gulp',
subtitle: 'Success!',
message: 'Scss task completed!',
sound: 'Pop'
}))
.pipe($.browserSync.stream());
});
// concat translate and minify js
gulp.task('webpack', () => {
return gulp.src(pkg.paths.src.js + pkg.vars.jsName)
.pipe($.newer(pkg.paths.src.assets + pkg.vars.siteJsName))
.pipe($.plumber({ errorHandler: onError }))
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest(pkg.paths.src.assets))
.pipe($.browserSync.stream());
});
gulp.task('default', ['serve'], () => {
return process.env.NODE_ENV === 'dev';
});
gulp.task('build', ['serve'], () => {
return process.env.NODE_ENV === 'prod';
});
webpack.config.js:
const webpack = require('webpack'),
pkg = require('./package.json'),
debug = process.env.NODE_ENV !== 'prod';
module.exports = {
context: __dirname,
devtool: debug ? 'inline-sourcemap' : null,
entry: pkg.paths.src.js + pkg.vars.jsName,
output: {
path: __dirname + pkg.paths.src.assets,
filename: pkg.vars.siteJsName
},
module: {
loaders: [
{
test: /(\.jsx|\.js)$/,
loader: 'babel',
exclude: /node_modules/
},
{
test: /(\.jsx|\.js)$/,
loader: 'eslint-loader',
exclude: /node_modules/
}
]
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false })
]
};

I figured out how to do it :
i had to add run-sequence to run task in a specific order and add the following:
package.json:
"scripts": {
"dev": "gulp develop",
"build": "gulp deploy"
}
Gulpfile:
setting a variable to safe the actual environment (useful to only execute apps in a task if a specific environment is set).
var config = {
env: process.env.NODE_ENV
};
tasks to set the environment:
gulp.task('set-dev-node-env', function () {
return process.env.NODE_ENV = config.env = 'dev'; // eslint-disable-line
});
gulp.task('set-prod-node-env', function () {
return process.env.NODE_ENV = config.env = 'prod'; // eslint-disable-line
});
the actual tasks :
gulp.task('default', ['serve']);
gulp.task('develop', ['set-dev-node-env'], function () {
return $.runSequence(
'default'
);
});
gulp.task('deploy', ['set-prod-node-env'], function () {
return $.runSequence(
'default'
);
});

Related

Remove console on browser when loading react app with npm start via webpack-dev-server

So after npm build and npm run , why does my react application open with console on the screen? It was not happening when my packages were "webpack-cli": "^4.2.0" and "webpack-dev-server": "^3.11.1". Upgrading them is causing this issue. How can we fix this?
My package.json contains (devDependencies)
"clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^7.0.0",
"webpack": "^5.11.0",
"webpack-bundle-analyzer": "^4.3.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.3",
"webpack-manifest-plugin": "2.2.0",
"webpack-merge": "^5.7.2"
"eslint-webpack-plugin": "^2.1.0",
"html-webpack-plugin": "5.3.2",
"scripts": {
"start": "webpack serve --config config/webpack.config.js --env TARGET_ENV=development --env app=web --port 3000",
"build": "webpack --config config/webpack.config.js --env TARGET_ENV=production",
"build:staging": "webpack --config config/webpack.config.js --env TARGET_ENV=staging"
}
webpack.config.js
const { merge } = require("webpack-merge");
//const commonConfig = require("./webpack.common.js");
const paths = require("./paths");
const webpack = require("webpack");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ESLintPlugin = require("eslint-webpack-plugin");
const getClientEnvironment = require("./env");
module.exports = (env) => {
const targetEnv = env.TARGET_ENV;
const mode = targetEnv === "development" ? "development" : "production";
process.env.NODE_ENV = mode;
// Source maps are resource heavy and can cause out of memory issue for large source files.
// const shouldUseSourceMap = webpackEnv === "development";
const commonConfig = {
mode: mode,
// Where webpack looks to start building the bundle
entry: {
web: paths.src + "/web.tsx",
},
// Where webpack outputs the assets and bundles
resolve: {
extensions: [".tsx", ".ts", ".js"],
fallback: {
util: require.resolve("util/"),
},
modules: ["node_modules", "./src"],
},
// Customize the webpack build process
plugins: [
new webpack.ProvidePlugin({
process: "process/browser",
}),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV is set to production
// during a production build.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(getClientEnvironment(targetEnv).stringified),
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/,
}),
// Removes/cleans build folders and unused assets when rebuilding
new CleanWebpackPlugin(),
// Copies files from target to destination folder
new CopyWebpackPlugin({
patterns: [
{
from: paths.public,
to: paths.build,
globOptions: {
ignore: ["**/*.html"],
},
},
{
from: paths.appPath + "/web.config",
to: paths.build,
},
],
}),
// Generates an HTML file from a template
// Generates deprecation warning: https://github.com/jantimon/html-webpack-plugin/issues/1501
new HtmlWebpackPlugin({
//favicon: paths.src + "/images/favicon.png",
template: paths.public + "/web.html", // template file
chunks: ["vendor", "web"],
filename: "web.html", // output file
inject: true,
}),
new HtmlWebpackPlugin({
template: paths.public + "/crossplatform.html", // template file
chunks: ["vendor", "crossplatform"],
filename: "crossplatform.html", // output file
inject: true,
}),
new ESLintPlugin({
// Plugin options
extensions: ["js", "jsx", "ts", "tsx"],
}),
],
// Determine how modules within the project are treated
module: {
rules: [
// JavaScript: Use Babel to transpile JavaScript files
{
test: /\.(ts|js)x?$/,
include: paths.src,
//exclude: /node_modules/,
loader: "babel-loader",
options: {
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
// Babel sourcemaps are needed for debugging into node_modules
// code. Without the options below, debuggers like VSCode
// show incorrect code and set breakpoints on the wrong lines.
//sourceMaps: shouldUseSourceMap,
//inputSourceMap: shouldUseSourceMap,
},
},
// Images: Copy image files to build folder
{ test: /\.(?:ico|gif|png|jpg|jpeg)$/i, type: "asset/resource" },
// Fonts and SVGs: Inline files
{ test: /\.(woff(2)?|eot|ttf|otf|svg|)$/, type: "asset/inline" },
],
},
};
const envConfig = require(`./webpack.${mode}.js`)({ app: env.app });
return merge(commonConfig, envConfig);
};
webpack.development.js
const webpack = require("webpack");
const paths = require("./paths");
module.exports = (args) => {
return {
// Control how source maps are generated
devtool: "cheap-module-source-map",
output: {
//path: paths.build,
publicPath: "./",
filename: "[name].js",
},
// Needed because of an issue with webpack dev server HMR with Webpack https://github.com/webpack/webpack-dev-server/issues/2758
target: "web",
// Spin up a server for quick development
devServer: {
historyApiFallback: {
index: "/" + args.app + ".html",
},
open: true,
devMiddleware: {
publicPath: "/",
},
hot: true,
// By default files from `contentBase` will not trigger a page reload.
// watchContentBase: true,
},
module: {
rules: [
// Styles: Inject CSS into the head with source maps
{
test: /\.(css)$/,
use: [
"style-loader",
{
loader: "css-loader",
//options: { sourceMap: true },
},
],
},
],
},
};
};

ERROR in Entry Module not found: Error: Can't resolve '*source*'

I am following a course on Udemy which is about Wordpress development. Following the course I came up with this problem, I was trying to add google maps to a custom post type, for that I needed to update javascript file. But whenever I am running 'gulp scripts', this error occurs. I have no idea about node, gulp, webpack. I am just following the course. I looked up on the internet for a long time on this issue but found nothing.
I am using XAMPP. And before this, 'gulp watch' was working fine and php scripts were getting updated just fine.
gulpfile.js:-
var gulp = require('gulp'),
settings = require('./settings'),
webpack = require('webpack'),
browserSync = require('browser-sync').create(),
postcss = require('gulp-postcss'),
rgba = require('postcss-hexrgba'),
autoprefixer = require('autoprefixer'),
cssvars = require('postcss-simple-vars'),
nested = require('postcss-nested'),
cssImport = require('postcss-import'),
mixins = require('postcss-mixins'),
colorFunctions = require('postcss-color-function');
gulp.task('styles', function() {
return gulp.src(settings.themeLocation + 'css/style.css')
.pipe(postcss([cssImport, mixins, cssvars, nested, rgba, colorFunctions, autoprefixer]))
.on('error', (error) => console.log(error.toString()))
.pipe(gulp.dest(settings.themeLocation));
});
gulp.task('scripts', function(callback) {
webpack(require('./webpack.config.js'), function(err, stats) {
if (err) {
console.log(err.toString());
}
console.log(stats.toString());
callback();
});
});
gulp.task('watch', function(done) {
browserSync.init({
notify: false,
proxy: settings.urlToPreview,
ghostMode: false
});
gulp.watch('./**/*.php', function(done) {
browserSync.reload();
done();
});
gulp.watch(settings.themeLocation + 'css/**/*.css', gulp.parallel('waitForStyles'));
gulp.watch([settings.themeLocation + 'js/modules/*.js', settings.themeLocation + 'js/scripts.js'], gulp.parallel('waitForScripts'));
done();
});
gulp.task('waitForStyles', gulp.series('styles', function() {
return gulp.src(settings.themeLocation + 'style.css')
.pipe(browserSync.stream());
}))
gulp.task('waitForScripts', gulp.series('scripts', function(cb) {
browserSync.reload();
cb()
}))
webpack.config.js:-
const path = require('path'),
settings = require('./settings');
module.exports = {
entry: {
App: settings.themeLocation + "js/scripts.js"
},
output: {
path: path.resolve(__dirname, settings.themeLocation + "js"),
filename: "scripts-bundled.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
},
mode: 'development'
}
settings.js:
exports.themeLocation = '/wp-content/themes/fictional-university-theme/';
exports.urlToPreview = 'localhost/imuni';
I had the same error the solution is simple add a DOT before /wp-content/:
exports.themeLocation = './wp-content/themes/fictional-university-theme/';
exports.urlToPreview = 'localhost/imuni';

Gulp webpack load jquery only once

I've got two Gulp tasks in my gulpfile.js. It's used for a website.
The first one compiles with webpack the main js file, used on all pages of the site (mainly visuals), and combines it to a single file.
gulp.task('scripts', function(callback) {
let firstBuildReady = false;
function done(err, stats) {
firstBuildReady = true;
if (err) { // hard error, see https://webpack.github.io/docs/node.js-api.html#error-handling
return; // emit('error', err) in webpack-stream
}
gulplog[stats.hasErrors() ? 'error' : 'info'](stats.toString({
colors: true
}));
}
let options = {
output: {
publicPath: '/js/',
filename: isDevelopment ? '[name].js' : '[name]-[chunkhash:10].js'
},
watch: isDevelopment,
devtool: isDevelopment ? 'cheap-module-inline-source-map' : false,
module: {
loaders: [{
test: /\.js$/,
//include: path.join(__dirname, "app/src/scripts/modules"),
loader: 'babel-loader',
query: {
presets: ["env"]
}
}]
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
]
};
if (!isDevelopment) {
options.plugins.push(new AssetsPlugin({
filename: 'scripts.json',
path: __dirname + '/app/manifest',
processOutput(assets) {
for (let key in assets) {
assets[key + '.js'] = assets[key].js.slice(options.output.publicPath.length);
delete assets[key];
}
return JSON.stringify(assets);
}
}));
}
return gulp.src(jsSRC)
.pipe(plumber({
errorHandler: notify.onError(err => ({
title: 'Scripts',
message: err.message
}))
}))
.pipe(named(function(file){
return 'app'
}))
.pipe(webpackStream(options, null, done))
.pipe(gulpIf(!isDevelopment, uglify()))
.pipe(gulp.dest(jsDIST))
.on('data', function() {
if (firstBuildReady) {
callback();
}
});
});
The second one compiles each js module as a single file - some js scripts, used on special pages. These scripts are included only there where needed.
gulp.task('webpack', function(callback) {
let firstBuildReady = false;
function done(err, stats) {
firstBuildReady = true;
if (err) {
return;
}
gulplog[stats.hasErrors() ? 'error' : 'info'](stats.toString({
colors: true
}));
}
let options = {
output: {
publicPath: '/js/',
filename: isDevelopment ? '[name].js' : '[name]-[chunkhash:10].js'
},
watch: isDevelopment,
devtool: isDevelopment ? 'cheap-module-inline-source-map' : false,
module: {
loaders: [{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ["env"]
}
}]
},
plugins: [
new webpack.NoEmitOnErrorsPlugin()
]
};
if (!isDevelopment) {
options.plugins.push(new AssetsPlugin({
filename: 'webpack.json',
path: __dirname + '/app/manifest',
processOutput(assets) {
for (let key in assets) {
assets[key + '.js'] = assets[key].js.slice(options.output.publicPath.length);
delete assets[key];
}
return JSON.stringify(assets);
}
}));
}
return gulp.src('app/src/scripts/modules/*.js')
.pipe(plumber({
errorHandler: notify.onError(err => ({
title: 'Webpack',
message: err.message
}))
}))
.pipe(named())
.pipe(webpackStream(options, null, done))
.pipe(gulpIf(!isDevelopment, uglify()))
.pipe(gulp.dest(jsDIST))
.on('data', function() {
if (firstBuildReady) {
callback();
}
});
});
But I have to include Jquery in every single file for the second task, otherwise it's not compiled. But Jquery is included in the main app.js file.
How can I solve it?
Thanks
Since it sounds like you're using a somewhat exotic way of loading JS in your application (instead of approaches like require.ensure), your easiest option may be to use Webpack externals when building your individual modules. Your main script/page will have to ensure that jQuery is globally exposed (like under window.$ or window.jQuery). Then, for your webpack config, include something like this:
{
// ...
externals: {
jquery: '$'
}
}
This will substitute $ for all require('jquery') calls instead of including jquery in each JS bundle.

Configure Webpack with Electron to use ES6 imports?

I am trying to use Webpack since I want to use ES modules in my Electron application but having some hurdles. I just want to use import in my main as well as renderer processes.
My application structure is as follows -
- src/ // contains basic html, css & js
- index.html // <h1>Hello World</h1>
- style.css // is empty
- app.js // console.log('it works 🙈')
- app/ // contains electron code
- main_window.js
- custom_tray.js
- index.js // entry point for electron application
- dist/ // output bundle generated from webpack
- bundle.js
My index.js file looks like -
import path from "path";
import { app } from "electron";
import MainWindow from "./app/main_window";
import CustomTray from "./app/custom_tray";
let win = null,
tray = null;
app.on("ready", () => {
// app.dock.hide();
win = new MainWindow(path.join("file://", __dirname, "/src/index.html"));
win.on("closed", () => {
win = null;
});
tray = new CustomTray(win);
});
My main_window.js file looks like -
import { BrowserWindow } from "electron";
const config = {
width: 250,
height: 350,
show: false,
frame: false,
radii: [500, 500, 500, 500],
resizable: false,
fullscreenable: false
};
class MainWindow extends BrowserWindow {
constructor(url) {
super(config);
this.loadURL(url);
this.on("blur", this.onBlur);
this.show();
}
onBlur = () => {
this.hide();
};
}
export default MainWindow;
My custom_tray.js looks like -
import path from "path";
import { app, Tray, Menu } from "electron";
const iconPath = path.join(__dirname, "../src/assets/iconTemplate.png");
class CustomTray extends Tray {
constructor(mainWindow) {
super(iconPath);
this.mainWindow = mainWindow;
this.setToolTip("Thirsty");
this.on("click", this.onClick);
this.on("right-click", this.onRightClick);
}
onClick = (event, bounds) => {
const { x, y } = bounds;
const { width, height } = this.mainWindow.getBounds();
const isMac = process.platform === "darwin";
if (this.mainWindow.isVisible()) {
this.mainWindow.hide();
} else {
this.mainWindow.setBounds({
x: x - width / 2,
y: isMac ? y : y - height,
width,
height
});
this.mainWindow.show();
}
};
onRightClick = () => {
const menuConfig = Menu.buildFromTemplate([
{
label: "Quit",
click: () => app.quit()
}
]);
this.popUpContextMenu(menuConfig);
};
}
export default CustomTray;
And my webpack.main.config.js looks like -
const path = require("path");
const config = {
entry: "./index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
module: {
rules: [{ test: /\.js$/, exclude: /node_modules/, use: "babel-loader" }]
},
stats: {
colors: true
},
target: "electron-main",
devtool: "source-map"
};
module.exports = config;
And my webpack.renderer.config.js looks like -
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const config = {
entry: "./src/app.js",
output: {
path: path.resolve(__dirname, "dist/renderer"),
filename: "app.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader"
},
{
test: /\.css$/,
use: {
loader: "css-loader",
options: {
minimize: true
}
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
use: {
loader: "url-loader",
query: {
limit: 10000,
name: "imgs/[name].[ext]"
}
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
use: {
loader: "url-loader",
query: {
limit: 10000,
name: "fonts/[name].[ext]"
}
}
}
]
},
stats: {
colors: true
},
target: "electron-renderer",
devtool: "source-map",
plugins: [
new CopyWebpackPlugin([
{ from: "src/app.css" },
{ from: "src/assets", to: "assets/" }
]),
new HtmlWebpackPlugin({
filename: "index.html",
template: path.resolve(__dirname, "./src/index.html"),
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true
}
})
]
};
module.exports = config;
My scripts in package.json look like
"scripts": {
"dev:main": "webpack --mode development --config webpack.main.config.js",
"dev:renderer": "webpack --mode development --config webpack.renderer.config.js",
"dev:all": "npm run dev:main && npm run dev:renderer",
"build:main": "webpack --mode production --config webpack.main.config.js",
"build:renderer": "webpack --mode production --config webpack.renderer.config.js",
"build:all": "npm run build:main && npm run build:renderer",
"prestart": "npm run build:all",
"electron": "electron dist/index.js",
"start": "npm run electron",
}
Currently my application creates a dist/bundle.js but when I run electron dist/bundle.js it doesn't work. I get it, it might be because it does not contain src folder but when I copy src folder into dist it still doesn't work.
Firstly, I run npm run dev:main to generate dist/bundle.js then I run npm run dev:renderer to generate dist/renderer/bundle.js & then I run npm run start to start my electron application.
It gives me error "Uncaught Exception: Error: Requires constructor call at new MainWindow" which is in index.js where I call constructor new MainWindow()
I just want to use ES6 in all my JS files. Is there any boilerplate because the ones I found have tons of additional stuff like React JS & all plus a huge number of optimizations ?
After 8 days I found the answer finally. It works with ESM in Electron.
I've made a repo that is minimum & lets you write ESM with Electron.
The complete code can be found at https://github.com/deadcoder0904/electron-webpack-sample
Its very minimal so it should be easy to understand.

Cannot find module bundle

Somewhere in development this error started showing, I can't pinpoint where it comes from. The error is to 'broad' for my knowledge. I'm using webpack and gulp. If anyone can point me in the right direction.
I can post more code, but you'll need to tell me what files. The app works as it should, REST, pages loading, etc.. Only the css is not showing.
Starting gatling-rsync-deamon...
Starting containers...
Starting vagrant_redis_1
Starting vagrant_mongo_1
Starting vagrant_app_1
Connection to 127.0.0.1 closed.
launching stream...
[14:39:00] Requiring external module babel-register
[14:39:14] Using gulpfile /var/www/app/gulpfile.babel.js
[14:39:14] Starting 'set-dev-env'...
NODE_ENV will be set to development...
[14:39:14] Finished 'set-dev-env' after 310 μs
[14:39:14] Starting 'backend-watch'...
[14:39:14] Backend warming up...
[14:39:14] Starting 'frontend-watch'...
[14:39:15] Finished 'frontend-watch' after 694 ms
[14:39:15] Starting 'server'...
[14:39:15] Finished 'server' after 1.55 ms
Webpack-dev-server listening at localhost:9090.
module.js:340
throw err;
^
Error: Cannot find module '/var/www/app/build/bundle'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:945:3
[14:39:20] Finished 'backend-watch' after 5.25 s
[14:39:20] Starting 'dev'...
[14:39:20] Finished 'dev' after 3.46 μs
Hash: 5e15e9e5b2fd1c868120
Version: webpack 1.13.0
gulpfile.babel.js
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import gulp from 'gulp';
import gutil from 'gulp-util';
import nodemon from 'nodemon';
import path from 'path';
import jsdoc from 'gulp-jsdoc3';
import WebpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
// import backendConfig from './config/webpack.backend.config.js';
// import frontendConfig from './config/webpack.frontend.config.js';
import configs from './config/webpack.config';
import jsdocConfig from './config/jsdoc.config';
const [frontendConfig, backendConfig] = configs;
const FRONTEND_PORT = 8085;
const BACKEND_PORT = 9090;
function onBuild(err, stats) {
if (err) {
throw new Error(err);
}
console.log(stats.toString());
}
// Default: list all tasks.
gulp.task('default', () => {
console.log('Available commands: dev, build');
});
// Start frontend
gulp.task('frontend', (done) => {
webpack(frontendConfig).run((err, stats) => {
onBuild(err, stats);
done();
});
});
// Start frontend watch
gulp.task('frontend-watch', () => {
const webpackDevserver = new WebpackDevServer(webpack(frontendConfig), {
publicPath: frontendConfig.output.publicPath,
stats: { colors: true },
historyApiFallback: true,
proxy: {
'*': `http://localhost:${BACKEND_PORT}`
}
});
webpackDevserver.listen(BACKEND_PORT, 'localhost', (err, result) => {
if (err) {
console.log(err);
}
else {
console.log(`Webpack-dev-server listening at localhost:${BACKEND_PORT}.`);
}
});
});
// Start backend
gulp.task('backend', (done) => {
webpack(backendConfig).run((err, stats) => {
onBuild(err, stats);
done();
});
});
// Start backend watch
gulp.task('backend-watch', (done) => {
gutil.log('Backend warming up...');
let firedDone = false;
webpack(backendConfig).watch(100, (err, stats) => {
if (!firedDone) { done(); firedDone = true; }
onBuild(err, stats);
nodemon.restart();
});
});
//
// gulp.task('run', ['set-dev-env', 'backend-watch'], () => {
// nodemon({
// execMap: {
// js: 'node'
// },
// script: path.join(__dirname, 'build/backend'),
// ignore: ['*'],
// watch: ['foo/'],
// ext: 'noop'
// }).on('restart', () => {
// console.log('Patched!');
// });
// });
// Set NODE_ENV to development
gulp.task('set-dev-env', () => {
console.log('NODE_ENV will be set to development...');
process.env.NODE_ENV = 'development';
});
// Set NODE_ENV to production
gulp.task('set-prod-env', () => {
console.log('NODE_ENV will be set to production...');
process.env.NODE_ENV = 'production';
});
// Start server
gulp.task('server', () => {
nodemon({
execMap: {
js: 'node'
},
script: path.join(__dirname, 'build/bundle'),
ignore: ['*'],
watch: ['foo/'],
ext: 'noop'
}).on('restart', () => {
console.log('Server restarted!');
});
});
// Generate docs
gulp.task('docs', (cb) => {
// gulp.src(['README.md', './client/**/*.js', './server/**/*.js'], { read: false })
// .pipe(jsdoc(jsdocConfig, cb));
});
// Build project
gulp.task('build', ['set-prod-env', 'build-js']);
// Build backend & frontend
gulp.task('build-js', ['backend', 'frontend']);
// Watch backend & frontend
gulp.task('watch', ['backend-watch', 'frontend-watch']);
// Start development session
gulp.task('dev', ['set-dev-env', 'backend-watch', 'frontend-watch', 'server']);
webpack.config
import webpack from 'webpack';
import path from 'path';
import fs from 'fs';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const embedFileSize = 50000;
const nodeModules = {};
fs.readdirSync('node_modules')
.filter(module => {
return ['.bin'].indexOf(module) === -1;
})
.forEach(mod => {
nodeModules[mod] = 'commonjs ' + mod;
});
const frontendConfig = {
entry: [
'webpack-hot-middleware/client',
path.join(__dirname, '../client/index.js')
],
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'build', 'public')
},
devtool: 'sourcemap',
plugins: [
new HtmlWebpackPlugin({
template: './client/public/index.html',
inject: 'body',
filename: 'index.html'
}),
new webpack.ProvidePlugin({
'Promise': 'es6-promise',
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
'__DEV__': JSON.stringify(process.env.NODE_ENV)
})
],
module: {
preloaders: [
{ test: /\.js$/, loader: 'eslint'}
],
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.json?$/,
loader: 'json'
},
{
test: /\.css$/,
loader: 'style-loader!css-loader?modules&&importLoaders=1&localIdentName=[name]---[local]---[hash:base64:5]!postcss-loader'
},
{
test: /\.less$/,
loader: "style!css!less"
},
{ test: /\.svg/,
loader: 'url?limit=' + embedFileSize + '&mimetype=image/svg+xml'
},
{ test: /\.png$/,
loader: 'url?limit=' + embedFileSize + '&mimetype=image/png'
},
{ test: /\.jpg/,
loader: 'url?limit=' + embedFileSize + '&mimetype=image/jpeg'
},
{ test: /\.gif/,
loader: 'url?limit=' + embedFileSize + '&mimetype=image/gif'
},
{
test: /\.(otf|eot|ttf|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url?limit=' + embedFileSize
}
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.json', '.css']
},
};
const serverConfig = {
entry: './server/server.js',
output: {
path: path.join(__dirname, '../build'),
filename: 'bundle.js'
},
devtool: 'sourcemap',
target: 'node',
// do not include polyfills or mocks for node stuff
node: {
console: false,
global: false,
process: false,
Buffer: false,
__filename: false,
__dirname: false
},
externals: nodeModules,
plugins: [
// enable source-map-support by installing at the head of every chunk
new webpack.BannerPlugin('require("source-map-support").install();',
{raw: true, entryOnly: false})
],
module: {
loaders: [
{
// transpile all .js files using babel
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel'
}
]
}
};
export default [frontendConfig, serverConfig];
My answer for now is based on your pasted code. When I get more info, then I will edit this answer.
Im not sure If I can find remotely correct solution for you. But your problem is probably with public path which is added to webpack and to WebpackDevServer. WebpackDevServer doesn't see your js code which is bundled in bundle.js
Change your target to "web" instead of node. You should compile for a web type of environment most likely and not a node.js like environment.
target: 'web',

Categories

Resources