pixi.js import issue with gulp & webpack - gulp

I have this gulp config file: (I removed some functions that do not interact with js)
const { src, dest, parallel, series, watch } = require('gulp')
const notify = require('gulp-notify')
const sourcemaps = require('gulp-sourcemaps')
const browserSync = require('browser-sync').create()
const del = require('del')
const webpackStream = require('webpack-stream')
const uglify = require('gulp-uglify-es').default
function scripts() {
return src('./src/assets/js/pages/*.js')
.pipe(
webpackStream({
mode: 'development',
output: {
filename: '[name].js',
},
optimization: {
splitChunks: {
chunks: 'all',
},
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [['#babel/preset-env']],
},
},
},
],
},
})
)
.pipe(sourcemaps.init())
.pipe(uglify().on('error', notify.onError('')))
.pipe(sourcemaps.write('.'))
.pipe(dest('./app/assets/js'))
.pipe(browserSync.stream())
}
function watchFiles() {
browserSync.init({
server: {
baseDir: './app',
},
})
watch('./src/*.html', htmlInclude)
watch('./src/partials/**/*.html', htmlInclude)
watch('./src/assets/scss/**/*.scss', styles)
watch('./src/assets/images/**/*', imgToApp)
watch('./src/assets/svg/**.svg', svg)
watch('./src/assets/fonts/**/*', fonts)
watch('./src/assets/js/**/*.js', scripts)
watch('./src/assets/fav.ico', favIcon)
}
function favIcon() {
return src('./src/assets/fav.ico').pipe(dest('./app/assets/'))
}
function clean() {
return del(['app/*'])
}
module.exports = {
styles,
watchFiles,
default: series(
clean,
parallel(favIcon, htmlInclude, imgToApp, svg, fonts, styles, scripts),
watchFiles
),
}
So, when I try to import Pixi.js
import * as PIXI from 'pixi.js';
my js code doesn't work at all and the worst thing is that there are no errors in the console.
Also I need hsl-to-hex module in my project and I just import it and everything works
I tried this variant of importing import PIXI from 'pixi.js/dist/pixi.js';
Also tried to use some gulp plugins, but I not really understand what they do, so it didn't give any result

Related

Webpack is not copying images to dist folder

I'm starting with webpack, but I'm really new on this and I'm stuck right now.
My project copies my fonts correctly but not images. Now the only way I am able to make it work is by copying my images manually to the dist/img folder.
This is my config:
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require('webpack');
var path = require("path");
module.exports = {
entry: './src/app.js',
output: {
path: path.resolve(__dirname + '/dist'),
filename: 'app.bundle.js'
// publicPath: '/dist',
},
module: {
rules:[
{
test:/\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ["css-loader?sourceMap","resolve-url-loader","sass-loader?sourceMap"],
// publicPath: '/dist'
})
},
{
test: /\.(woff2?|ttf|otf|eot|svg)$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}]
// loader: 'file-loader?name=/fonts/[name].[ext]'
},
{
test: /\.(jpg|png|gif)$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'img/',
publicPath:'img/'
}
}]
}
]
},
devServer: {
contentBase: path.join(__dirname, "/dist"),
compress: true,
port: 8000,
stats: "errors-only",
open: true
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new ExtractTextPlugin("styles.css"),
new HtmlWebpackPlugin({
title: 'Project',
hash:true,
template: './src/index.html'
})
]
}
I've tried several configurations but no solution. I also searched here for any solution but without success.
If your images are only referenced in HTML files as <img> tags, webpack by default won't pick them up because it doesn't parse HTML. You have at least 2 choices:
Use CopyWebpackPlugin to copy the files to wherever you want, this at least removes the "manual" part you mention
Move your images references to styles, where webpack can pick them up via the scss loader you are using. For example
background-image: url("img/foo.png");
There is also option import image trough JavaScript.
import '../img/image.png';
I had this problem. I didn't know that the file-loader only copies the images if you run a build, and doesn't do anything while using webpack-dev-server. My solution was just:
$ npx webpack

How to chain in Gulp: Typescript to Babel to Webpack with source map?

I'm trying to create a gulp task that transforms
TS -> (ES6) -> Babel -> (ES5) -> Webpack -> [bundle.js, bundle.js.map]
where the source map maps back to the original TS code.
How can I do this with gulp?
So far, I've managed to get it working from TS -> ES6 -> Babel -> ES5
// Build
gulp.task("build", ["clean"], () => {
const tsProject = ts.createProject("tsconfig.json", {});
const sourceMapOptions = {
sourceRoot: __dirname+"/src"
};
return tsProject.src()
.pipe(sourcemaps.init())
// Typescript
.pipe(tsProject())
.js
// Babel
.pipe(babel({
presets: ["es2015"],
plugins: ["transform-runtime"]
}))
// Webpack <-- ????
.pipe(webpack({})) // <-- ????
.pipe(sourcemaps.write(".", sourceMapOptions))
.pipe(gulp.dest("./dist"));
});
But have no idea how to add webpack to the mix.
Since there are still no answers, here's what I ended up doing.
I had to do it in two steps (idea from here):
Typescript -> (ES6) -> Babel -> (ES5)
Webpack to bundle
Using source-map-loader to pick up the generated source maps
/** Typescript -> ES6 -> Babel -> ES5 */
gulp.task("ts-babel", function () {
const tsconfig = {
target: "es6",
lib: ["es5", "dom"]
}
const babelconfig = {
presets: ["es2015"],
plugins: ["transform-runtime"]
}
const tsProject = ts.createProject(tsconfig);
return gulp
.src("src/**/*.ts")
.pipe(sourcemaps.init())
.pipe(tsProject())
.js
.pipe(babel(babelconfig))
.pipe(sourcemaps.write("."))
.pipe(gulp.dest("build/es5"));
})
/** Webpack bundle */
gulp.task("webpack", ["ts-babel"], function () {
const config = {
devtool: "source-map",
output: {
filename: "app.bundle.js"
},
module: {
preLoaders: [
{
test: /\.js$/,
loader: "source-map-loader"
}
]
}
}
return gulp
.src("build/es5/**/*.js")
.pipe(webpack(config))
.pipe(gulp.dest("build/bundle"));
})

Webpack: "Module parse failed"

1.When I Execute command line, the Error is as follows:
D:\mypro\Demo\webpack\webpackgulp>webpack
Hash: d6b7d6bad8ca0746b6ec
Version: webpack 1.13.1
Time: 46ms
[0] ./src/main.js 0 bytes [built] [failed]
ERROR in ./src/main.js
Module parse failed: D:\mypro\Demo\webpack\webpackgulp\src\ma
ken (7:16)
You may need an appropriate loader to handle this file type.
2.Related configuration is as follows:
(1)Document structure:
(2)webpack.config.js:
module.exports = {
entry: "./src/main.js",
output: {
filename: "build.js",
path: __dirname
},
module: {
loaders: [
{
test: /\.less$/,
loader: "style!css!less"
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
plugins: []
};
(3)Entry file is main.js:
// css
require('../css/main.less');
var ContentMode = React.createClass({
render: function(){
return (
<div className="ContentMode">
<div class="contents">{this.props.contents}</div>
{this.props.children}
</div>
)
}
});
var Page = React.createClass({
render: function(){
return (
<div className="homepage">
<ContentMode contents ="longen">this is one comment</ContentMode >
<ContentMode contents ="longen2">this is two comment</ContentMode >
</div>
)
}
});
/* init to content container */
React.render(
React.createElement(Page,null),document.getElementById("content")
);
(4)node_modules:
3.How to solve this problem?

Browserify + shim on jquery and signalR not working

I'm using gulp + browserify to bundle my source but i got always the same error : jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file. SignalR get $ = undefined...
I split my source into two bundle : vendor and app. Vendor bundle get lib's id from packages.json and the bundle require it. App bundle get main entry and i passe id's lib to this bundle with bundle.external.
Here my packages.json :
"browser": {
"angular-notify": "./node_modules/angular-notify/dist/angular-notify.js",
"angular-i18n": "./node_modules/angular-i18n/angular-locale_fr.js",
"jquery": "./node_modules/jquery/dist/jquery.js",
"signalR": "./node_modules/ms-signalr-client/jquery.signalr-2.2.0.js",
"moment": "./node_modules/moment/moment.js",
"moment-business": "./Scripts/Vendor/js/moment-business.js"
},
"browserify": {
"transform": [
"browserify-shim"
]
},
"browserify-shim": {
"jquery": "$",
"signalR": {
"depends": [
"jquery:jQuery"
]
},
"moment": "moment"
}
Here my gulp taks :
'use strict';
import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import browserify from 'browserify';
import browserifyInc from 'browserify-incremental';
import ngHtml2Js from 'browserify-ng-html2js';
import shim from 'browserify-shim';
import xtend from 'xtend';
import tsify from 'tsify';
import babelify from 'babelify';
import minifyify from 'minifyify';
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import browserSync from 'browser-sync';
import packageJson from './package.json';
const $ = gulpLoadPlugins();
let bs = browserSync.create();
let dependenciesCss = [
'bootstrap',
'font-awesome',
'animate.css'
];
let externalDependenciesjs = [
'signalR',
'moment-business'
];
let dependenciesJs = Object.keys(packageJson.dependencies).filter(
key => (
dependenciesCss.every(
libCssName => (key.trim() !== libCssName)
)
)
);
dependenciesJs = dependenciesJs.concat(externalDependenciesjs);
/*************************************
* SCRIPTS (build) *
*************************************/
let extensions = ['.js', '.json', '.ts'];
let bundler = browserify(xtend(browserifyInc.args, {
entries: 'Scripts/App/app.ts',
debug: true,
extensions,
cache: {},
packageCache: {},
fullPaths: true
}))
.external(dependenciesJs)
.plugin(tsify, {
target: 'es6'
})
.transform(babelify.configure({
extensions,
}))
.plugin(minifyify, {
map: 'app.min.js.map',
output: 'Scripts/Dist/app.min.js.map'
});
function compile() {
bundler.on('log', $.util.log);
browserifyInc(bundler, {
cacheFile: './.tmp/browserify-cache.json'
});
$.util.log('Bundling JS ...');
return bundler.bundle()
.pipe($.plumber({
errorHandler: browserifyError
}))
.on('error', browserifyError)
.pipe(source('app.min.js'))
.pipe(buffer())
.pipe($.size({
title: 'scripts'
}))
.pipe(gulp.dest('Scripts/Dist'))
.pipe($.if(bs.active, bs.stream({
once: true
})));
}
let bundlerVendor = browserify(xtend(browserifyInc.args, {
debug: true,
extensions,
cache: {},
packageCache: {},
fullPaths: true
}))
.require(dependenciesJs)
.plugin(minifyify, {
map: 'vendor.min.js.map',
output: 'Scripts/Dist/vendor.min.js.map'
});
function compileVendor() {
bundlerVendor.on('log', $.util.log);
browserifyInc(bundlerVendor, {
cacheFile: './.tmp/browserify-vendor-cache.json'
});
$.util.log('Bundling vendor JS ...');
return bundlerVendor.bundle()
.pipe($.plumber({
errorHandler: browserifyError
}))
.on('error', browserifyError)
.pipe(source('vendor.min.js'))
.pipe(buffer())
.pipe($.size({
title: 'scripts vendor'
}))
.pipe(gulp.dest('Scripts/Dist'))
.pipe($.if(bs.active, bs.stream({
once: true
})));
}
function browserifyError(err) {
error(err);
this.end();
}
Vendor bundle haven't entry point, it only require lib.
Here my app bundle entry :
/// <reference path="_references.ts" />
import 'signalR';
import 'moment';
import 'moment-business';
import 'moment-range';
import 'angular';
import 'angular-messages';
import 'angular-mocks';
import 'angular-animate';
import 'angular-file-upload';
import 'angular-notify';
import 'angular-i18n';
import 'angular-ui-bootstrap';
import 'angular-ui-router';
import 'angular-vs-repeat';
import 'postal';
import Route from './route';
import * as Configuration from './config';
import register from './registerModule';
import {camelize} from './tools';
let modules: Array<string> = [
appName + '.Controllers',
appName + '.Directives',
appName + '.Filters',
appName + '.Services',
appName + '.Factory',
appName + '.Constant'];
modules.forEach((moduleName: string): ng.IModule => angular.module(moduleName, []));
register();
modules.push('templates');
modules.push('ui.router');
modules.push('ui.bootstrap');
modules.push('angularFileUpload');
modules.push('ngAnimate');
modules.push('ngMessages');
modules.push('cgNotify');
modules.push('vs-repeat');
angular.module(appName, modules);
angular.module(appName)
.config(
['$stateProvider', '$urlRouterProvider', '$locationProvider',
($stateProvider: ng.ui.IStateProvider,
$urlRouterProvider: ng.ui.IUrlRouterProvider,
$locationProvider: ng.ILocationProvider): Route => (
new Route($stateProvider, $urlRouterProvider, $locationProvider)
)
]);
angular.module(appName)
.config(['$logProvider', ($logProvider: ng.ILogProvider): void => {
$logProvider.debugEnabled(Configuration.ENABLED_CONSOLE_DEBUG);
}
]);
angular.module(appName)
.config(
['$provide', ($provide: ng.auto.IProvideService): void => {
/* tslint:disable:no-any */
$provide.decorator('$exceptionHandler', ['$delegate', '$window', ($delegate: Function, $window: ng.IWindowService): any => {
return (exception: any, cause: string): any => {
/* tslint:enable:no-any */
// utilisation du service $delegate pour formatter le message à afficher dans la console
$delegate(exception, cause);
};
}]);
}
]);
angular.module(appName)
.config(
['$provide', '$httpProvider', ($provide: ng.auto.IProvideService, $httpProvider: ng.IHttpProvider): void => {
$provide.factory('customHttpInterceptor', ['$q', ($q: ng.IQService) => {
return {
/* tslint:disable:no-any */
'response': (response: any): any=> (camelize(response))
/* tslint:enable:no-any */
};
}]);
$httpProvider.interceptors.push('customHttpInterceptor');
}]);
angular.module(appName).run(runAngular);
runAngular.$inject = ['$rootScope', '$location', '$log'];
function runAngular($rootScope: ng.IRootScopeService,
$location: ng.ILocationService,
$log: ng.ILogService): void {
'use strict';
$log.debug('Démarrage de l\'application : ', appName);
}
I already try to use browserify-shim transform with option global but this not work too.
You still have to import jQuery into your code. The depends section of browserify-shim just tells it that jQuery comes before SignalR in the bundle. It doesn't say that any time you import SignalR that it will automatically import jQuery first.
The exact solution depends on whether SignalR is expecting jQuery to simply be present in the bundle, whether it expects jQuery to be present on the window object, or whether SignalR is a jQuery plugin that could potentially need attaching manually to the $ object.
The first solution I'd try is to simply import jQuery before you import SignalR:
/// <reference path="_references.ts" />
import $ from 'jquery';
import 'signalR';
// Rest of app.js........

Webpack paths issue with es6

I have a structure like this but am having an error when trying to run webpack
/app
/main.js
/foo.js
/dist
index.html ( uses <script src="dist/bundle.js"></script>)
webpackconfig.js
in main.js:
import foo from './foo'
var foo = new foo()
foo.js:
export class foo {
constructor() {
loadScript("//www.parsecdn.com/js/parse-1.4.0.min.js", init());
}
}
webpackconfig.js
My config:
module.exports = {
context: __dirname + "/app",
entry: "./main.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
devtool: "#source-map",
module: {
loaders: [
// Transpile any JavaScript file:
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}
]
},
resolve: {
// you can now require('file') instead of require('file.js')
extensions: ['', '.js', '.json']
}
}
but I get this error:
ERROR in ./main.js
Module not found: Error: Cannot resolve module 'foo'
It is because webpack try to load foo from node_modules directory.
You have to specify the path of your module like this:
import foo from './foo'