I'm at a point in my Gulp usage that it's starting to make sense splitting tasks up into separate files.
For this, I was hoping to use gulp-load-plugins, but although my task runs, Browser-Sync doesn't appear to fire / do anything.
Here's my stripped back setup. Not sure where I'm going wrong!
gulpfile.js
var gulp = require('gulp'),
plugins = require('gulp-load-plugins')();
function getTask(task) {
return require('./gulp/tasks/' + task)(gulp, plugins);
}
gulp.task('browser-sync', getTask('browser-sync'));
gulp.task('bs-reload', getTask('bs-reload'));
gulp.task('scripts', getTask('scripts'));
gulp.task('default', ['browser-sync'], function(){
gulp.watch('src/js/**/*.js', ['scripts']);
});
scripts.js (Gulp Task)
var browserSync = require('browser-sync').create();
module.exports = function(gulp, plugins) {
return function() {
return gulp.src([
'src/js/plugins/**',
'src/js/app.js',
'!src/js/{libraries,libraries/**}'
])
.pipe(plugins.plumber({
errorHandler: function(error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(plugins.concat('app.js'))
.pipe(gulp.dest('dist/js/'))
.pipe(plugins.rename({
suffix: '.min'
}))
.pipe(plugins.uglify({
preserveComments: 'none'
//preserveComments: 'some'
}))
.pipe(gulp.dest('dist/js/')) // Seems okay up until here...
.pipe(browserSync.reload({ // ...but this never seems to fire!
stream: true
}));
};
};
You'll notice I'm requiring Browser-Sync in my scripts.js file, but this is because doing plugins.Browser-Sync wasn't working. I read somewhere that this is because Browser-Sync is not actually a Gulp plugin.
So whilst I don't get any errors and Browser-Sync appears to start up...from then on, my scripts task works, but it doesn't fire the BrowserSync part.
Any help greatly appreciated!
PS, Incase it helps, here's my package.json file (notice that above I'm presenting you a stripped back version of my gulpfile.js).
package.json
{
"name": "MichaelPumo",
"version": "1.0.0",
"description": "A frontend Gulp project for WordPress by Michael Pumo.",
"main": "gulpfile.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "MichaelPumo",
"license": "MIT",
"devDependencies": {
"browser-sync": "2.6.5",
"gulp-postcss": "~6.0.0",
"autoprefixer-core": "~5.2.1",
"gulp-sourcemaps": "~1.5.2",
"gulp-concat": "2.5.2",
"gulp-plumber": "1.0.0",
"gulp-rename": "1.2.2",
"gulp-sass": "2.0.4",
"gulp-uglify": "1.2.0",
"gulp": "~3.9.0",
"node-neat": "~1.7.2",
"gulp-svgmin": "~1.2.0",
"gulp-image-optimization": "~0.1.3",
"gulp-load-plugins": "~1.0.0"
}
}
For anyone wondering or in the dark about this, note that by default gulp-load-plugins will only work with NPM packages that are prefixed with 'gulp-'.
Fortunately, you can change this behaviour and pass the search as an option like so:
gulpfile.js
var gulp = require('gulp'),
plugins = require('gulp-load-plugins')({
pattern: '*'
});
In your tasks, you can now reference Browser-Sync as plugins.browserSync like so:
browser-sync.js (Gulp Task)
'use strict';
module.exports = function(gulp, plugins) {
return function() {
plugins.browserSync.init({
port: 8080,
proxy: {
target: 'http://localhost:8888/my-website-path/'
}
});
};
};
Hope this helps someone else!
Related
I recently updated #vue's webpack and submodules to v5 following this. This was necessary because web workers were not working with v4. Now my problem is that I'm not able to debug the code and I don't know where to start. I accept any suggestion that helps me diagnose the problem
The code runs normally, it just doesn't stop on breakpoints anymore. My vue.config.js has a configuration in the devtoolModuleFilenameTemplate that if I'm not mistaken it was supposed to work with .ts files, I've tried to remove it and it didn't help.
I searched around here and couldn't find anyone with a similar problem. My current version is at 5.0.8 but I also tried 5.0.1.
vue.config.js:
/* eslint-disable */
const CompilerSfc = require('#vue/compiler-sfc')
const parse = CompilerSfc.parse
CompilerSfc.parse = (source, options) => {
return parse(source, Object.assign({ pad: true }, options))
}
module.exports = {
devServer: {
allowedHosts: 'all',
port: 5000,
host: '0.0.0.0',
},
configureWebpack: {
devtool: 'source-map',
output: {
devtoolModuleFilenameTemplate: (info) => {
if (info.allLoaders === '') {
// when allLoaders is an empty string the file is the original source
// file and will be prefixed with src:// to provide separation from
// modules transpiled via webpack
const filenameParts = ['src://']
if (info.namespace) {
filenameParts.push(info.namespace + '/')
}
filenameParts.push(info.resourcePath.replace(/^\.\//, ''))
return filenameParts.join('')
} else {
// otherwise we have a webpack module
const filenameParts = ['webpack://']
if (info.namespace) {
filenameParts.push(info.namespace + '/')
}
filenameParts.push(info.resourcePath.replace(/^\.\//, ''))
const isVueScript =
info.resourcePath.match(/\.vue$/) &&
info.query.match(/\btype=script\b/) &&
!info.allLoaders.match(/\bts-loader\b/)
if (!isVueScript) {
filenameParts.push('?' + info.hash)
}
return filenameParts.join('')
}
},
},
},
}
launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "vue.js: chrome",
"request": "launch",
"type": "chrome",
"url": "http://localhost:5000",
"webRoot": "${workspaceFolder}/src"
}
]
}
You can put debugger key directly in your code, instand of breakpoint in vscode. Then, debug with your browser.
Here is an example :
Hope it hopes :)
Trying to deploy a smart contract using Hardhat but getting configuration error.
Here is the complete error details
Error HH9: Error while loading Hardhat's configuration.
You probably tried to import the "hardhat" module from your config or a file imported from it.
This is not possible, as Hardhat can't be initialized while its config is being defined.
All the plug-ins seem to be have been installed correctly.
deploy.js
const hre = require("hardhat");
async function main() {
const TestContract = await hre.ethers.getContractFactory("TestContract");
const superInstance = await TestContract.deploy("TestContractHAT", "SMC");
await superInstance.deployed();
console.log("contract was deployed to:", superInstance.address());
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
package.json
{
"name": "Test",
"version": "1.0.0",
"description": "This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, a sample script that deploys that contract, and an example of a task implementation, which simply lists the available accounts.",
"main": "hardhat.config.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#nomiclabs/hardhat-ethers": "^2.0.5",
"#nomiclabs/hardhat-waffle": "^2.0.3",
"chai": "^4.3.6",
"ethereum-waffle": "^3.4.4",
"ethers": "^5.6.2"
},
"dependencies": {
"dotenv": "^16.0.0",
"hardhat": "^2.9.3"
}
}
Hardhat.config
const { ethers } = require("hardhat");
require('#nomiclabs/hardhat-waffle');
require("#nomiclabs/hardhat-ethers");
require('#openzeppelin/hardhat-upgrades');
require("dotenv").config();
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.2",
networks: {
mumbai: {
url: process.env.MUMBAI_URL,
account: process.env.PRIVATE_KEY
}
}
};
Any pointers are helpful. Thanks
As the error states, you are importing hardhat module in your hardhat configuration.
You probably tried to import the "hardhat" module from your config or a file imported from it. This is not possible, as Hardhat can't be initialized while its config is being defined.
Remove the line
const { ethers } = require("hardhat");
and the error should disappear
Just remove
const { ethers } = require("hardhat");
or
const { hardhatArguments } = require("hardhat");
or any other that requires hardhat
My vite config looks like this.
I want to have two entry points, as you can see in build.lib.entry I have the entry for my library, in this case src/main.js, but I would also like to have one entry for my project because I am testing locally.
// vite.config.js
const path = require('path')
module.exports = {
build: {
lib: {
entry: path.resolve(__dirname, 'src/main.js'),
name: 'MyLib'
},
rollupOptions: {
// make sure to externalize deps that shouldn't be bundled
// into your library
external: ['vue'],
output: {
// Provide global variables to use in the UMD build
// for externalized deps
globals: {
vue: 'Vue'
}
}
}
}
}
I tried adding the following code inside module.exports, but it didn'T work.
entry: path.resolve(__dirname, 'src/app.js'),
https://vitejs.dev/guide/build.html#library-mode
In the vite discussions on github it seems you do it with something like this.
https://github.com/vitejs/vite/discussions/1736#discussioncomment-413068
build: {
rollupOptions: {
input: {
'entry-point-a': path.resolve(__dirname, 'src/entry-point-a.tsx'),
'entry-point-b': path.resolve(__dirname, 'src/entry-point-b.tsx'),
},
}
},
It looks like vite does not support multiple entries. You can use two vite configuration files.
eg. package.json :
"scripts": {
"build": "vite build --config vite.config.js",
"build:lib": "vite build --config vite-lib.config.js",
},
The symlink support is still not officially available in react-native https://github.com/facebook/metro/issues/1.
It's actually possible to use symlinks in the package.json with npm (not yarn)
{
"name": "PROJECT",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"my_module1": "file:../shared/my_module1/",
"my_module2": "file:../shared/my_module2/",
"react": "16.8.3",
"react-native": "0.59.5",
},
"devDependencies": {
"babel-jest": "24.7.1",
"jest": "24.7.1",
"metro-react-native-babel-preset": "0.53.1",
"react-test-renderer": "16.8.3"
},
"jest": {
"preset": "react-native"
}
}
Although we will get my_module1 does not exist in the Haste module map
To fix this we could do before a metro.config.js (formerly rn-cli.config.js)
const path = require("path")
const extraNodeModules = {
/* to give access to react-native-firebase for a shared module for example */
"react-native-firebase": path.resolve(__dirname, "node_modules/react-native-firebase"),
}
const watchFolders = [
path.resolve(__dirname, "node_modules/my_module1"),
path.resolve(__dirname, "node_modules/my_module2"),
]
module.exports = {
resolver: {
extraNodeModules
},
watchFolders,
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false
}
})
}
}
Unfortunately it doesn't work anymore on react-native 0.59 The app is reloading, but changes in the source code are not reflected in the app. Anyone has a clue to achieve this?
I had a similar issue and found haul.
Follow haul getting started instructions.
Add your local dependencies with file:../ e.g:
// package.json
"dependencies": {
"name-of-your-local-dependency": "file:../"
}
reinstall node_modules with yarn --force
Start the development server by yarn start (haul will replace your start script)
Run react-native run-android or/and react-native run-ios
None of the answers I found worked for me and it seems symlinks are not going to be supported anytime soon (see: https://github.com/facebook/metro/issues/1), so I had to do it manually.
I am using onchange npm package and running that in my local package: onchange 'dist/**/*.js' -- cp -R ./dist ../../app/node_modules/#author/packagename
That worked for me to achieve development and testing, while not breaking anything for production releases. I hope this can save my peers a few headaches.
After a few years working on this, we found a reliable way using yarn.
Add your local dependencies with are inside a folder file:../CompanyPackages/package e.g:
// package.json
"dependencies": {
"local-package": "file:../CompanyPackages/local-package"
}
Use a custom metro.config.js
const path = require("path")
const { mapValues } = require("lodash")
// Add there all the Company packages useful to this app
const CompanyPackagesRelative = {
"CompanyPackages": "../CompanyPackages",
}
const CompanyPackages = mapValues(CompanyPackagesRelative, (relativePath) =>
path.resolve(relativePath)
)
function createMetroConfiguration(projectPath) {
projectPath = path.resolve(projectPath)
const watchFolders = [...Object.values(CompanyPackages)]
const extraNodeModules = {
...CompanyPackages,
}
// Should fix error "Unable to resolve module #babel/runtime/helpers/interopRequireDefault"
// See https://github.com/facebook/metro/issues/7#issuecomment-508129053
// See https://dushyant37.medium.com/how-to-import-files-from-outside-of-root-directory-with-react-native-metro-bundler-18207a348427
const extraNodeModulesProxy = new Proxy(extraNodeModules, {
get: (target, name) => {
if (target[name]) {
return target[name]
} else {
return path.join(projectPath, `node_modules/${name}`)
}
},
})
return {
projectRoot: projectPath,
watchFolders,
resolver: {
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
extraNodeModules: extraNodeModulesProxy,
},
}
}
module.exports = createMetroConfiguration(__dirname)
You can use yalc. Yalc will simulate a package publish without actually publishing it.
Install it globally:
npm i -g yalc
In your local package:
yalc publish
In the application:
yalc add package-name && yarn
After you made some changes to the package, you can just run
yalc push
and it will automatically update every app that uses your local package
Could never get my own environment working using any other suggestions, but found a hack that works well (though not ideal) that can be easily set up in just a few lines of code and without changing your RN project configuration.
Use fs.watch for changes recursively in the directory where you're working on your library, and copy the updates over whenever there's been a change:
import fs from 'fs'
const srcDir = `./your-library-directory`
const destDir = `../your-destination-directory`
fs.watch("./src/", {recursive: true}, () => {
console.log('copying...')
fs.cp(srcDir, destDir, { overwrite: true, recursive: true }, function() {
console.log('copied')
})
})
Only two things are required.
1.yarn --force
2.yarn start
then select android for running option
I'm starting with a gulp-fontgen project, but I got an error when I run it with gulp command:
TypeError: Cannot read property 'replace' of undefined
My gulpfile:
var gulp = require('gulp');
var fontgen = require('./node_modules/gulp-fontgen');
gulp.task('fontgen', function() {
return gulp.src("./assets/*.{ttf,otf}")
.pipe(fontgen({
dest: "./dest/"
}));
});
gulp.task('default', ['fontgen']);
My package.json:
{
"name": "garagord-webfont",
"version": "1.0.0",
"description": "",
"main": "gulpfile.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"gulp": "^3.9.1",
"gulp-fontgen": "^0.2.4"
}
}
Entire terminal output:
$ gulp
[11:26:24] Using gulpfile /Volumes/B/Documentos/tipografia-garagord/Gulp/gulpfile.js
[11:26:24] Starting 'fontgen'...
/Volumes/B/Documentos/tipografia-garagord/Gulp/node_modules/fontfacegen/lib/configure.js:19
_.config_file = _.source.replace(_.extension, '') + '.json';
^
TypeError: Cannot read property 'replace' of undefined
at module.exports (/Volumes/B/Documentos/tipografia-garagord/Gulp/node_modules/fontfacegen/lib/configure.js:19:30)
at module.exports (/Volumes/B/Documentos/tipografia-garagord/Gulp/node_modules/fontfacegen/lib/fontfacegen.js:16:18)
at DestroyableTransform._transform (/Volumes/B/Documentos/tipografia-garagord/Gulp/node_modules/gulp-fontgen/lib/gulp-fontgen.js:47:31)
at DestroyableTransform.Transform._read (/Volumes/B/Documentos/tipografia-garagord/Gulp/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:159:10)
at DestroyableTransform.Transform._write (/Volumes/B/Documentos/tipografia-garagord/Gulp/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:147:83)
at doWrite (/Volumes/B/Documentos/tipografia-garagord/Gulp/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:313:64)
at writeOrBuffer (/Volumes/B/Documentos/tipografia-garagord/Gulp/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:302:5)
at DestroyableTransform.Writable.write (/Volumes/B/Documentos/tipografia-garagord/Gulp/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:241:11)
at write (/Volumes/B/Documentos/tipografia-garagord/Gulp/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:623:24)
at flow (/Volumes/B/Documentos/tipografia-garagord/Gulp/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:632:7)
The gulp-fontgen plugin is horribly broken. Just take a look at the source code:
return _through2.default.obj(function (file, enc, callback) {
// options.source = file.path;
(0, _fontfacegen2.default)(options);
undefined.push(file);
return callback();
});
The commented out line above is what is causing your error. The source option is not passed along to fontfacegen. Even if you uncomment that line there's a freaking undefined.push(file); in there which cannot possibly work (lesson: don't take drugs, kids, and always write your unit tests).
My suggestion: don't use gulp-fontgen. The plugin is really just a thin wrapper around fontfacegen. You can easily replace it by using fontfacegen directly in combination with map-stream:
var gulp = require('gulp');
var fontfacegen = require('fontfacegen');
var map = require('map-stream');
gulp.task('fontgen', function() {
return gulp.src("./assets/*.{ttf,otf}")
.pipe(map(function(file, cb) {
fontfacegen({
source: file.path,
dest: './dest/'
});
cb(null, file);
}));
});