Trying to write a vuepress plugin - plugins

(The doc on writing a plugin is pretty sparse...)
THE GOAL
Create a plugin to add headers to a page.
THE ATTEMPT
Created a plugin following guidelines and an example plugin (that presumably works...) to do something similar.
THE ISSUE
Plugin won't load.
config.js
plugins: [
[
'vuepress-plugin-headertags',
{ headerTags: ["<script src='https://cdn.jsdelivr.net/npm/netlify-identity-widget#1.5.2/build/netlify-identity-widget.min.js'></script>"]}
]
],
(the <script> tag is what I'm trying to insert, in this instance.
PLUGIN index.js
const { path } = require('path')
// was: const { path } = require('#vuepress/shared-utils')
// dunno. No documentation on this...
// got the current version from the 'default-theme' code
module.exports = (options) => ({
define () {
return {
headerTags: options.headerTags || []
}
},
enhanceAppFiles () {
return [path.resolve(__dirname, 'enhanceAppFile.js')]
},
globalUIComponents: ['HeaderTags']
})
PLUGIN INSTALLATION
I published it to npm as vuepress-plugin-headertags, and then installed it with:
yarn add -D vuepress-plugin-headertags
Here's the relevant package.json content:
{
"name": "vuepress-netlifycms",
"version": "0.0.0",
"scripts": {
"dev": "vuepress dev",
"build": "vuepress build",
"debug": "node --nolazy --inspect=9229 /home/rickb/.yarn/bin/vuepress build"
},
"devDependencies": {
"vuepress": "^0.14.8",
"vuepress-plugin-headertags": "^1.0.3"
},
"dependencies": {}
}
VUEPRESS INSTALLATION
I cloned the vuepress repo from git and did a yarn link, which makes it globally available. With that, I can trace it in the debugger via the 'debug' script.
TRACING
I've followed the VP source code in the debugger and get to resolvePathPackage() in moduleResolver.js. The incoming path is not correct:
/home/(...)/VuePress-NetlifyCMS/vuepress-plugin-headertags
It should be:
/home/(...)/VuePress-NetlifyCMS/node_modules/vuepress-plugin-headertags
At any rate, it doesn't resolve, even after the 'normalization' process.
MORE EYES
I need more eyes on this to help me figure it out. The project is already up on github as 'rickbsgu/VuePress-NetlifyCMS.git'. If you do an install, the plugin will be in the project directory under 'node_modules/vuepress-plugin-headertags'
Any thoughts appreciated

And it works, now. Two problems:
Version I was running/debugging was not the same as the version in package.json. There is the vuepress executable and the vuepress libraries the plugin requires. The library was always the older version at runtime.
I needed to change the path import in index.html from const { path } = require('path') to const { path } = require('#vuepress/shared-utils'). That's my doc issue - I don't see that documented anywhere.
Thanks #Sun Haoran for getting me to look in the right place.

Related

How to add babel and polyfills to a RequireJs project?

I am working on a legacy project which uses RequireJs to load and resolve all the dependencies. It works fine on modern browsers, but i need to add support for IE11.
I tried to use babel 7 with #babel/preset-env with following .babelrc
{
"presets": [
["#babel/preset-env", {
"useBuiltIns": "usage",
"corejs": 3,
"targets": {
"browsers" : ["ie>=11"]
},
"modules": false
}]
],
"compact": false
}
the import statements injected by the preset as following
import "core-js/modules/es.function.name.js";
cause error "import statements can't be used outside a module". Even when I use modules: "amd", then core-js is imported as
define(["core-js/modules/es.array.filter.js", "core-js/modules/es.object.to-string.js", "core-js/modules/es.string.includes.js", "core-js/modules/es.function.name.js", "core-js/modules/es.regexp.exec.js", "core-js/modules/es.string.split.js", "core-js/modules/es.string.small.js", "core-js/modules/es.string.search.js"], function (_esArrayFilter, _esObjectToString, _esStringIncludes, _esFunctionName, _esRegexpExec, _esStringSplit, _esStringSmall, _esStringSearch) {
"use strict";
//...
});
which throws error like "define is not defined in require.js".
When using useBuiltIns: "entry", and then including core-js as
require(["core-js", ../other modules], function(corejs, ...){
}
)
in the main.js file, it fails to correctly resolve the path of the files even though I have included the path to core-js in require.config.paths.
I tried #babel/runtime and #babel/plugin-transform-runtime but no luck there.
So my question is what would be the best way to add babel and the required polyfills in my RequireJs project so that it is compatible with IE 11?

ERR_REQUIRE_ESM require of of ES Module not supported how can I fix this? on file-type package

I've a outdated app that uses very older few packages those doesn't support ES Module as an example file-type package. So if you setup babel and node HTTP server with and then install file-type package then start building and running will throw error message like below:
Error [ERR_REQUIRE_ESM]: require() of ES Module E:\test\testbabel\node_modules\file-
type\index.js from E:\test\testbabel\dist\index.js not supported.
Instead change the require of E:\test\testbabel\node_modules\file-type\index.js in
E:\test\testbabel\dist\index.js to a dynamic import() which is available in all CommonJS
modules.
at Object.<anonymous> (E:\test\testbabel\dist\index.js:10:17) {
code: 'ERR_REQUIRE_ESM'
}
I tried this on a fresh project though my old project has an outdated config or so, It still throwing this error
Here are my index.js codes
import http from 'http';
import { fileTypeFromFile } from 'file-type';
const server = http.createServer((req, res) => {
res.end('Hello from the server');
}).listen(4001);
console.log('Server is up and running');
export default server;
file package.json.
{
"name": "testbabel",
"version": "1.0.0",
"description": "test babel with http or express",
"main": "index.js",
"scripts": {
"build": "babel index.js -d dist",
"start": "npm run build && node dist/index.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.17.10",
"#babel/core": "^7.18.2",
"#babel/plugin-transform-modules-commonjs": "^7.18.2",
"#babel/preset-env": "^7.18.2"
},
"dependencies": {
"file-type": "^17.1.1"
}
}
I just tried to import the package and got the errors above.
attempt:
I thought a converter might help so used #babel/plugin-transform-modules-commonjs but still didn't help, and seems no effect on including that package
I'm not sure but added some tweaks on package.json like "type": "module" "type": "commonjs" didn't help at all.
what is the easiest solution for this issue and how do we fix it?
Note: I saw people were going back to the supported package instead of new one which doesn't make sense to me as a solution.
Option1(babel with mocha): Rename "index.js" to "index.mjs" and modify file-type's pacakage.json ("index.js" to "index.mjs"), then leave Babel to transpile for you.
// babel-register.js
const babel_register = require("#babel/register").default;
babel_register({
ignore: [
// Only work on Project-wide configuration
// overrides ignore can transpile packages(modules) from node_modules (https://babeljs.io/docs/en/babel-register/#ignores-node_modules-by-default)
],
});
Use babel.config instead of .babelrc
//.mocharc.js
require("./babel-register");
module.exports = {
// https://github.com/mochajs/mocha/blob/v8.4.0/example/config/.mocharc.js
ui: "bdd",
timeout: 5000,
recursive: true,
};
Option2(babel only): Using dynamic import expression
async function doSomething() {
const {fileTypeFromStream} = await import("file-type");
}
and
["#babel/preset-env", {
exclude: ["proposal-dynamic-import"]
}]
Avoiding Babel tanspile dynamic import expression

Unable to resolve module when using babel module resolver + eslint + index files in react application

I am trying to use babel module resolver plugin with eslint + create react app but I am unable to start the application, getting the error
internal/modules/cjs/loader.js:1237
throw err;
^
SyntaxError: C:\Users\enisr\Desktop\projects\pcPartPicker\jsconfig.json:
Unexpected token } in JSON at position 166
at parse (<anonymous>)
I have set up a git repo showcasing the problem https://github.com/sgoulas/pcPartPicker
I have read the instructions in the docs and in the original repository and I am unable to configure it correctly.
My configuration files are the following:
.babelrc
{
"plugins": [
["module-resolver", {
"extensions": [
".js",
".jsx",
".es",
".es6",
".mjs"
],
"root": ["./src"],
"alias": {
"#components": "./src/components"
}
}
]
]
}
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["src/*"],
"#components/*": ["./src/components/*"],
}
}
}
webpack.config.dev.js
var path = require("path");
module.exports = {
include: path.appSrc,
loader: require.resolve("babel-loader"),
options: {
plugins: [
[
"module-resolver",
{
root: ["./src/App"],
alias: {
"#components": "./src/components",
},
},
],
],
cacheDirectory: true,
},
};
My component:
import { GPUtable, CPUtable } from "#components/Tables";
const App = () => {
return (
<>
<GPUtable />
<CPUtable />
</>
);
};
export default App;
There are some minor fixes you need to make (below), but the main issue is that Create React App does not expose the webpack config, you'll need to eject to edit that.
npm run eject
Merge the babel configs: delete the babel key + value at the bottom of the package.json, and paste the value into your bablrc ("presets": ["react-app"],).
Add import React from 'react'; to the top of App.js
Confirmed locally that the app will run.
Other suggested fixes
Your jsconfig has a trailing comma after the array value in #components/*. You need to remove it because JSON doesn’t support them.
You need to fix the include path in weback.config.dev.js. appSrc isn't something defined on the node path module. Try using path.resolve(__dirname, 'src') - the example in their docs is creating/importing a paths object with appSrc pointing to this value.
You're missing test: /\.(js|jsx|mjs)$/, in webpack.config.dev.js.

Gatsby not working paths deployed on the github pages (adding repo name in the url)

I deployed a gatsby website with the Github pages and I'm having errors like that:
Locally everything works perfectly, errors occur only on the server.
Seems like the server can not resolve paths correctly.
I'm adding unnecessary repository name after domain. How to remove that?
I tried changing some host options and deploying app again and once it worked properly, IDK why, then I made another deploy and it crushed again.
My gatsby.config:
const path = require("path");
const { title, keywords, description, author, defaultLang, trackingId } = require("./config/site");
module.exports = {
pathPrefix: "/lbearthworks",
siteMetadata: {
title,
keywords,
description,
author,
},
plugins: [
{
resolve: "gatsby-plugin-google-analytics",
options: {
trackingId,
},
},
{
resolve: "gatsby-plugin-manifest",
options: {
name: title,
short_name: "Lb",
start_url: "/",
background_color: "#212121",
theme_color: "#fed136",
display: "minimal-ui",
icon: "content/assets/gatsby-icon.png",
},
},
"gatsby-transformer-remark",
{
resolve: "gatsby-source-filesystem",
options: {
name: "markdown",
path: `${__dirname}/content`,
},
},
{
resolve: "gatsby-source-filesystem",
options: {
name: "images",
path: `${__dirname}/content/assets/images`,
},
},
"gatsby-plugin-eslint",
"gatsby-plugin-react-helmet",
"gatsby-transformer-sharp",
"gatsby-plugin-sharp",
"gatsby-plugin-offline",
{
resolve: "gatsby-plugin-sass",
options: {
data: `#import "core.scss";`,
includePaths: [path.resolve(__dirname, "src/style")],
},
},
...
],
};
Live version
Github Reository
When dealing with GitHub Pages you need to add an extra configuration to your build command, since you are adding a pathPrefix variable, you need to allow Netlify how to prefix those paths. Ideally, the build command should look like:
"deploy": "gatsby build --prefix-paths && gh-pages -d public"
In your case, because you are adding a file-based configuration (netlify.toml), your build command is:
[build]
command = "yarn && yarn testbuild"
publish = "public"
Note that testbuild is yarn test && yarn build, according to your repository.
So, one workaround is changing your package.json command to:
"testbuild": "yarn test && yarn build --prefix-paths && gh-pages -d public",
In addition, you should be in gh-pages branch as it shows the Gatsby's documentation:
When you run npm run deploy all contents of the public folder will be
moved to your repository’s gh-pages branch. Make sure that your
repository’s settings has the gh-pages branch set as the source to
deploy from.

electron-builder cannot find git repository although specifying

package.json
{
//some other config
"repository": "git#gitintsrv.domain.com/UserName/RepoName",
"scripts": {
"build": "build --win",
"ship": "build --win -p always"
}
}
electron-builder.yml
appId: com.xorchat.app.windows
publish:
provider: github
token: some_token
electron.js
const { app, BrowserWindow, ipcMain } = require('electron');
const { autoUpdater } = require("electron-updater");
let win; // this will store the window object
// creates the default window
function createDefaultWindow() {
win = new BrowserWindow({ width: 900, height: 680 });
win.loadURL(`file://${__dirname}/src/index.html`);
win.on('closed', () => app.quit());
return win;
}
// when the app is loaded create a BrowserWindow and check for updates
app.on('ready', function() {
createDefaultWindow()
autoUpdater.checkForUpdates();
});
// when the update has been downloaded and is ready to be installed, notify the BrowserWindow
autoUpdater.on('update-downloaded', (info) => {
win.webContents.send('updateReady')
});
// when receiving a quitAndInstall signal, quit and install the new version ;)
ipcMain.on("quitAndInstall", (event, arg) => {
autoUpdater.quitAndInstall();
})
When i am running npm run build i am receiving this error.
Error: Cannot detect repository by .git/config. Please specify "repository" in the package.json (https://docs.npmjs.com/files/package.json#repository).
Please see https://electron.build/configuration/publish
Where is the error?
I know it's probably too late, but in case you end up here as I did, here's how I solved it:
Add this to your package.json
"build": {
"publish": [{
"provider": "github",
"host": "github.<<DOMAIN>>.com",
"owner": "<<USER>>",
"repo": "<<NAME OF YOUR REPO (ONLY THE NAME)>>",
"token": "<<ACCESS TOKEN>>"
}]
}
I think the issue is that electron cannot parse corporate github urls, or something.
*********** EDIT:
Make a electron-builder.yml in the root folder, with the following content
appId: com.corporate.AppName
publish:
provider: github
token: <<ACCESS TOKEN>>
host: github.corporate.com
owner: <<User/ Org>>
repo: <<repo name>>
Don't forget to include this file on your .gitignore
This use to be a specific issue with Electron Builder 19x, and it has since been fixed:
https://github.com/electron-userland/electron-builder/issues/2785