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';
Related
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.
How i can specify different filename for different entry output?
For example:
module.exports = {
context: path.resolve(__dirname, 'assets'),
entry: {
vendor: ['react', 'react-dom', 'lodash', 'redux'],
app: './src/app.js'
}
output: {
path: path.resolve(__dirname, (isDevelopment) ? 'demo' : 'build'),
filename: (isDevelopment) ? '[name].js' : '[name][chunkhash:12].js'
}
}
To receive output like this
build
-- index.html
-- app.2394035ufas0ue34.js
-- vendor.js
So browser will cache vendor.js with all libraries. Since i don't plan to migrate to any major new release anytime soon and often.
And still being able to break cache for app.js with every update required.
is there some kind of option to set output as
output: {
app: {
...
},
vendor: {
...
},
}
Here is working code:
entry: {
'./build/app': './src/app.js',
'./build/vendor': VENDOR_LIBS // or path to your vendor.js
},
output: {
path: __dirname,
filename: '[name].[chunkhash].js'
},
Add this code into your webpack plugins array as last element of an array.
plugins: [
... // place our new plugin here
]
function() {
this.plugin("done", function(stats) {
const buildDir = __dirname + '/build/';
const fs = require('fs');
var vendorTempFileName = '';
new Promise(function(resolve, reject) {
fs.readdir(buildDir, (err, files) => {
files.forEach(file => {
if (file.substr(0,6) === 'vendor') {
resolve(file);
}
});
});
}).then(function(file) {
fs.rename( buildDir + file, buildDir + 'vendor.js', function(err) {
if ( err ) console.log('ERROR: ' + err);
});
});
});
}
Output should be as follows:
It is considered bad practice to leave your files without chunkhashes, due to browser caching.
For Webpack 4 I added a quick-and-dirty done hook to rename my service worker script:
// Plugin to rename sw-[chunkhash].js back to sw.js
class SwNamePlugin {
apply(compiler) {
compiler.hooks.done.tap("SW Name Plugin", (stats) => {
const swChunk = stats.compilation.chunks.find((c) => c.name === "sw");
fs.rename(path.resolve(outDir, swChunk.files[0]), `${outDir}/sw.js`);
});
}
}
plugins.push(new SwNamePlugin());
This obviates the warning DeprecationWarning: Tapable.plugin is deprecated. Use new API on .hooks instead you'd see following loelsonk's answer.
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'
);
});
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',
I am building a basic blog project to practice using React, ES6, and Mocha test framework. I'm having trouble transpiling my ES6 tests and app code within my default Gulp task.
I get this error when I run the default task and change the contents of ./test/posts.js for the watch to take effect:
[11:17:29] Using gulpfile ~/WebstormProjects/blog/gulpfile.js
[11:17:29] Starting 'default'...
[11:17:29] Finished 'default' after 8.54 ms
stream.js:75
throw er; // Unhandled stream error in pipe.
^
Error: invalid argument
at pathToArray (/Users/christian/WebstormProjects/blog/node_modules/memory-fs/lib/MemoryFileSystem.js:44:10)
at MemoryFileSystem.mkdirpSync (/Users/christian/WebstormProjects/blog/node_modules/memory-fs/lib/MemoryFileSystem.js:139:13)
at MemoryFileSystem.(anonymous function) [as mkdirp] (/Users/christian/WebstormProjects/blog/node_modules/memory-fs/lib/MemoryFileSystem.js:279:34)
at Compiler.<anonymous> (/Users/christian/WebstormProjects/blog/node_modules/webpack/lib/Compiler.js:229:25)
at Compiler.applyPluginsAsync (/Users/christian/WebstormProjects/blog/node_modules/tapable/lib/Tapable.js:60:69)
at Compiler.emitAssets (/Users/christian/WebstormProjects/blog/node_modules/webpack/lib/Compiler.js:226:7)
at Watching.<anonymous> (/Users/christian/WebstormProjects/blog/node_modules/webpack/lib/Compiler.js:54:18)
at /Users/christian/WebstormProjects/blog/node_modules/webpack/lib/Compiler.js:403:12
at Compiler.next (/Users/christian/WebstormProjects/blog/node_modules/tapable/lib/Tapable.js:67:11)
at Compiler.<anonymous> (/Users/christian/WebstormProjects/blog/node_modules/webpack/lib/CachePlugin.js:40:4)
Process finished with exit code 1
webpack.config.js
var path = require('path');
var babel = require('babel-loader');
module.exports = {
entry: {
app: './app/js/blog.js',
test: './test/posts.js'
},
output: {
filename: '[name].bundle.js',
path: './build',
sourceMapFilename: '[name].bundle.map'
},
watch: true,
devtool: '#sourcemap',
module: {
loaders: [
{
loader: 'babel',
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
query: {
presets: ['react', 'es2015']
}
}
],
resolve: {
root: path.resolve('./app'),
extensions: ['', '.js']
}
}
};
gulpfile.js
var gulp = require('gulp');
var webpack = require('webpack-stream');
var watch = require('gulp-watch');
var babel = require('babel-loader');
var named = require('vinyl-named');
gulp.task('default', function() {
watch(['./app/**/*.js', './test/*.js'], function() {
return gulp.src(['./app/js/blog.js', './test/posts.js'])
.pipe(named())
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('./build'));
});
});
gulp.task('testBundle', function() {
gulp.src('./test/posts.js')
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('./build'));
});
posts.js
import expect from 'expect'
import { post, posts, addPost } from '../app/js/blog'
import { createStore } from 'redux'
describe('Blog', () => {
describe('posts', () => {
it('should be able to create a post', () => {
let store = createStore(posts);
store.dispatch(addPost('First Post', 'Blah blah blah'))
let blah = { id: 'First Post', content: 'Blah blah blah'}
expect(store.getState()).toEqual(blah)
});
it('should be able to create multiple posts', () => {
let store2 = createStore(posts);
store2.dispatch(addPost('Second Post', 'Shh'))
let expectedState1 = { id: 'Second Post', content: 'Shh' }
expect(store2.getState()).toEqual(expectedState1)
store2.dispatch(addPost('Third Post', 'Whatever'))
let expectedState2 = { id: 'Third Post', content: 'Whatever'}
expect(store2.getState()).toEqual(expectedState2)
})
});
});
Ultimately, I'd like the transpiled code to be found at ./build/blog.bundle.js and ./build/posts.bundle.js for ./app/js/blog.js and ./test/posts.js, respectively.
There were some issues with my webpack.config.js and gulpfile.js. Apparently, the path property within the output object in webpack.config.js was conflicting with gulp.dest('./build'). I also reformatted some things in the config file to mirror a working one. Below is the code that should work. Hopefully this helps others trying to accomplish the same thing.
I have gulp starting webpack to produce separate bundle files for app and test entry points. I also get sourcemaps for each of the bundles that are created. Now I can write tests and app code in ES6 and run them with Mocha within WebStorm!
gulpfile.js
var gulp = require('gulp');
var webpack = require('webpack-stream');
var watch = require('gulp-watch');
gulp.task('default', function() {
watch(['./app/**/*.js', './test/*.js'], function() {
return gulp.src(['./app/js/blog.js', './test/posts.js'])
.pipe(named())
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('./build'));
});
});
gulp.task('webpack', function() {
return gulp.src(['./app/js/blog.js', './test/posts.js'])
.pipe(named())
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('./build'));
});
webpack.config.js
var path = require('path');
var babel = require('babel-loader');
module.exports = {
entry: {
app: './app/js/entry.js',
test: './test/posts.js'
},
output: {
filename: '[name].bundle.js',
sourceMapFilename: '[name].bundle.map'
},
devtool: '#source-map',
module: {
loaders: [
{
loader: 'babel',
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
query: {
presets: ['react', 'es2015']
}
}
]
},
resolve: {
root: path.resolve('./app'),
extensions: ['', '.js']
}
};
entry.js
import { posts } from './blog'
import { createStore } from 'redux'
createStore(posts)
blog.js
const posts = (state = [], action) => {
switch (action.type) {
case 'ADD_POST':
return post(undefined, action)
default:
return state
}
}
const post = (state = {}, action) => {
switch (action.type) {
case 'ADD_POST':
return { id: action.name, content: action.content }
}
}
// action creator
const addPost = (name, content) => {
return {
type: 'ADD_POST',
name,
content
}
}
export { posts, post, addPost }