I'm new to javascript and vscode extension development.
I'm trying to write a vscode extension, doing execSync a python script.
The file structure:
src:
|-- extension.ts
|-- sidebar_test.ts
|-- test_py.py
the content of extension.js file:
import * as vscode from 'vscode';
import * as sidebar from './sidebar_test';
import * as cp from "child_process";
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
console.log('process cwd: ', process.cwd(), '. env: ', process.env);
console.log('extension path: ', context.extensionPath);
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
let disposable = vscode.commands.registerCommand('dp2000-upgrade.DP2000Upgrade', function () {
vscode.window.showInputBox({
ignoreFocusOut: true,
placeHolder: 'IP Addr:Port',
}).then(function (input_str) {
let options = { env: {LD_LIBRARY_PATH: '/data/huangxiaofeng/work/tvm0.9dev0/build', PYTHONPATH: '/data/huangxiaofeng/work/tvm0.9dev0/python'} };
cp.execSync(`python ./test_py.py ${input_str}`, options); // TODO: call python script test_py.py
}).then(function (msg) {
console.log('User input:' + msg);
});
});
context.subscriptions.push(disposable);
}
// this method is called when your extension is deactivated
export function deactivate(): void {}
the content of test_py.py:
#! /usr/bin/python3.6
# -*- coding:utf-8 -*-
import tvm
import sys
import tvm.rpc
print('test_py.py will run...')
ip_addr, ip_port = sys.argv[1].split(':')
remote = tvm.rpc.connect(ip_addr, int(ip_port))
add_func = remote.get_function('rpc.test_add')
print(add_func(10, 20))
The content of package.json
{
"name": "dp2000-upgrade",
"displayName": "DP2000升级插件Demo",
"description": "vscode插件Demo, 借助TVM实现远程刷写 NNP main.hex",
"publisher": "intellif",
"version": "0.0.1",
"engines": {
"vscode": "^1.63.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:dp2000-upgrade.DP2000Upgrade",
"onView:sidebar_test_id1"
],
"main": "./out/extension.js",
"contributes": {
"commands": [
{
"command": "dp2000-upgrade.DP2000Upgrade",
"title": "Upgrade DP2000"
}
]
},
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"pretest": "npm run compile && npm run lint",
"lint": "eslint src --ext ts",
"package": "npm ci && rimraf *.vsix && vsce package && vsce ls"
},
"devDependencies": {
"#types/vscode": "^1.63.0",
"#types/glob": "^7.2.0",
"#types/mocha": "^9.0.0",
"#types/node": "14.x",
"#typescript-eslint/eslint-plugin": "^5.9.1",
"#typescript-eslint/parser": "^5.9.1",
"eslint": "^8.6.0",
"glob": "^7.2.0",
"mocha": "^9.1.3",
"typescript": "^4.5.4",
"#vscode/test-electron": "^2.0.3"
},
"repository": {
"type": "git",
"url": "https://gitee.com/vaughnHuang/vscode_ext_sidebar_test"
}
}
When package the project to .vsix, the test_py.py not included.
So my question is: how to include src/test_py.py into the .vsix?
Related
Trying to build my electron app with typescript generated from the electron-quick-start-typescript project. I have added an additional module called auth.ts which is not recognised when I start the app. I am trying to reference it in renderer.ts with
import { myfunction } from './auth'
However I can see that it is getting converted into js. What could be causing this issue? Why can't my application see my new module?
Additionally here is my package.json file if that helps.
{
"name": "electron-quick-start-typescript",
"version": "1.0.0",
"description": "A minimal Electron application written with Typescript",
"scripts": {
"build": "tsc",
"watch": "tsc -w",
"lint": "eslint -c .eslintrc --ext .ts ./src",
"start": "npm run build && electron ./dist/main.js"
},
"repository": "https://github.com/electron/electron-quick-start-typescript",
"keywords": [
"Electron",
"quick",
"start",
"tutorial",
"demo",
"typescript"
],
"author": "GitHub",
"license": "CC0-1.0",
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^4.33.0",
"#typescript-eslint/parser": "^4.33.0",
"electron": "^16.0.2",
"eslint": "^7.32.0",
"typescript": "^4.5.2"
},
"dependencies": {
"node-fetch": "^2.6.1"
}
}
Found the answer. For anyone else having the same issue this resolved the issue -
Make sure nodeIntegration is enabled in main.js
webPreferences: {
nodeIntegration: true,
preload: path.join(__dirname, "preload.js"),
},
Index.html
replace:
<script src="./dist/renderer.js"></script>
with:
<script>
require("./dist/renderer.js");
</script>
I have a problem with "async" in babel and node js that i couldn't solve for days... the error bellow:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\BOOSTACKSTICK\BOOSTACK\node_modules\#babel\runtime\helpers\esm\asyncToGenerator.js [1] require() of ES modules is not supported. [1] require() of C:\BOOSTACKSTICK\BOOSTACK\node_modules\#babel\runtime\helpers\esm\asyncToGenerator.js from C:\BOOSTACKSTICK\BOOSTACK\prod-server\api\auth\auth-controller.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. [1] Instead rename asyncToGenerator.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\BOOSTACKSTICK\BOOSTACK\node_modules\#babel\runtime\helpers\esm\package.json.
I compile my dev-server folder to a prod-server with config bellow
package.json
"scripts": {
"serve": "vue-cli-service serve",
"build": "babel dev-server --out-dir prod-server && vue-cli-service build",
"lint": "vue-cli-service lint",
"dev": "concurrently \"babel dev-server --out-dir prod-server --watch\" \"nodemon prod-server/index.js\" \"npm run serve\" "
},
"devDependencies": {
"#babel/cli": "^7.12.1",
"#babel/core": "^7.12.3",
"#babel/node": "^7.12.1",
"#babel/plugin-transform-async-to-generator": "^7.12.1",
"#babel/plugin-transform-runtime": "^7.12.1",
"#babel/preset-env": "^7.12.1",
"#babel/runtime-corejs3": "^7.12.1",
"#vue/cli-plugin-babel": "^4.5.8",
"#vue/cli-plugin-eslint": "^4.5.8",
"#vue/cli-service": "^4.5.8",
"babel-eslint": "^10.1.0",
"compass-mixins": "^0.12.10",
"concurrently": "^5.3.0",
"core-js": "^3.6.5",
"css-loader": "^3.6.0",
"eslint": "^5.16.0",
},
.babelrc
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "usage", // or "entry"
"corejs": 3,
"targets": {
"node": "current"
}
}
]
],
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"corejs": 3
}
],
["#babel/plugin-proposal-class-properties"]
]
}
Environment
Node: v12.16.3
Babel: 7.12.3
**Simple code with "async" that causing a problem **
export async function index(req, res) {
return res.status(200).json({ user: "user" });
}
** Babel Output**
"use strict";
var _interopRequireDefault = require("C:/BOOSTACKSTICK/BOOSTACK/node_modules/#babel/runtime/helpers/interopRequireDefault");
var _Object$defineProperty = require("#babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.index = index;
var _regenerator = _interopRequireDefault(require("#babel/runtime-corejs3/regenerator"));
require("regenerator-runtime/runtime");
var _asyncToGenerator2 = _interopRequireDefault(require("C:/BOOSTACKSTICK/BOOSTACK/node_modules/#babel/runtime/helpers/esm/asyncToGenerator"));
//Check And Validate Request (LOGIN METHODE)
function index(_x, _x2) {
return _index.apply(this, arguments);
}
function _index() {
_index = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(req, res) {
return _regenerator.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", res.status(200).json({
user: "user"
}));
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _index.apply(this, arguments);
}
Possible Solution
the only workaround i tested to avoid this error is to modify manually the node_modules\#babel\runtime\helpers\esm\package.json to remove "type": module and remove import from node_modules\#babel\runtime\helpers\esm\asyncToGenerator.js
is it a bug or i'm doing something wrong?
Thank you in advance for your reply.
I have implemented simple rest api with nodejs and connection to database via typeorm. Here are some snippets of code which I wrote:
import {
Entity,
PrimaryGeneratedColumn,
Column,
Unique,
CreateDateColumn,
UpdateDateColumn
} from "typeorm";
import { Length, IsNotEmpty } from "class-validator";
import bcrypt from "bcryptjs";
#Entity()
#Unique(["username"])
export class User {
#PrimaryGeneratedColumn()
public id: number;
#Column()
#Length(4, 20)
username: string;
}
tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"emitDecoratorMetadata": true
},
"lib": [
"es2015"
]
}
package.json
{
"name": "node-with-ts",
"version": "1.0.0",
"description": "",
"main": "dist/app.js",
"scripts": {
"start": "tsc && node dist/app.js",
"test": "echo \"Error: no test specified\" && exit 1",
"tsc": "tsc",
"prod": "node ./dist/app.js",
"build": "npm install && tsc -p .",
"reset": "rm -rf node_modules/ && rm -rf dist/ && npm run build",
"migration:run": "ts-node ./node_modules/typeorm/cli.js migration:run"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#types/express": "^4.16.1",
"#types/node": "^12.7.5",
"nodemon": "^1.19.2",
"ts-node": "8.4.1",
"tslint": "^5.12.1",
"typescript": "^3.3.3"
},
"dependencies": {
"#types/bcryptjs": "^2.4.2",
"#types/body-parser": "^1.17.0",
"#types/cors": "^2.8.4",
"#types/helmet": "0.0.42",
"#types/jsonwebtoken": "^8.3.0",
"bcryptjs": "^2.4.3",
"body-parser": "^1.18.1",
"class-validator": "^0.9.1",
"cors": "^2.8.5",
"express": "4.17.1",
"helmet": "^3.21.1",
"jsonwebtoken": "^8.4.0",
"reflect-metadata": "^0.1.13",
"sqlite3": "^4.1.0",
"ts-node-dev": "^1.0.0-pre.32",
"typeorm": "^0.2.12"
}
}
I have pasted lots of code because I have no idea what is wrong. I am tryinf to run app via npm run start and it throws below error:
> tsc && node dist/app.js
/Users/workspace/node_typescript_project/src/entity/User.ts:1
(function (exports, require, module, __filename, __dirname) { import {
^^^^^^
SyntaxError: Unexpected token import
Although I able to build to project and it generates js codes but when it comes to run application it throws errors.
Your entities are probably not being referenced correctly in your Typeorm config file.
Try to see if you can get it to work with the following ormconfig.js file (pay special attention to the entities property:
// ormconfig.js at root of project
const isDevelopment = process.env.NODE_ENV === 'development';
module.exports = {
type: 'mysql',
host: process.env.MYSQL_HOST,
port: process.env.MYSQL_TCP_PORT,
username: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
synchronize: isDevelopment,
logging: isDevelopment,
entities: [
isDevelopment ? `src/**/*.entity.ts` : `dist/**/*.entity.js`,
],
migrations: [`src/migration/**/*.ts`],
subscribers: ['src/subscriber/**/*.ts'],
cli: {
entitiesDir: 'src/entity',
migrationsDir: 'src/migration',
subscribersDir: 'src/subscriber',
},
};
With this setup, I have ts-node working directly with my Typescript source files, and only in production do I use tsc to build. When building for prod, I need to reference the .js files inside of the dist folder.
I am trying to replicate the issue but couldn't replicate it. Just created a sample repo for above code.
https://github.com/pktippa/stackoverflow-questions/tree/master/58148222
Try a different import syntax, eg.:
import { bcrypt } from "bcryptjs";
Other import syntax examples can be found here.
Node.js does not handle ES6 syntax, with imports etc.
For that you have to transpile your ES6 code to ES5, you can do it with Babel => https://github.com/babel/example-node-server
If you don't want to use Babel, you can simply replace import by require:
const bcrypt = require("bcryptjs"); // same as 'import * as bcrypt from "bcryptjs";'
I'm having some issues while trying to glue together this two things.
Let me give you some context: I'm trying to build a desktop application based on a web application that I've developed in react and it's fully operative and the build process of react is done without any errors nor issues. The problem comes when I try to glue Electron + a React Built Project.
I'm having the following structure:
/ dist
/ node_modules
/ react-mobx-router
/ build
/ static
/ js
main.05ef4655.js
/ css
main.9d8efafe.css
index.html
index.js
At the index.js i have the following code that's basically the sample boilerplate code from electron demo app:
'use strict';
const electron = require('electron');
const app = electron.app;
// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();
// prevent window being garbage collected
let mainWindow;
function onClosed() {
// dereference the window
// for multiple windows store them in an array
mainWindow = null;
}
function createMainWindow() {
const win = new electron.BrowserWindow({
width: 1280,
height: 720,
minWidth: 1280,
minHeight: 720
});
win.loadURL(`file://${__dirname}/react-mobx-router/build/index.html`);
//win.loadURL(`http://localhost:3000`);
win.on('closed', onClosed);
return win;
}
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (!mainWindow) {
mainWindow = createMainWindow();
}
});
app.on('ready', () => {
mainWindow = createMainWindow();
});
I also have to manually change some paths at the react built index.html so it will look like:
<link href="./static/css/main.9d8efafe.css" rel="stylesheet">
instead of:
<link href="/static/css/main.9d8efafe.css" rel="stylesheet">
The second one get's the following errors:
file:///D:/static/css/main.9d8efafe.css Failed to load resource: net::ERR_FILE_NOT_FOUND
main.05ef4655.js Failed to load resource: net::ERR_FILE_NOT_FOUND
The point is that, when I launch the Electron app with yarn start (changing the paths I've told you previously) it launches without any error nor issue but only a blank screen, if I go to the files and look for them, they are correct and the code is inside, bundled and all that react-create-app stuff does.
This is the default configuration of the package.json that comes with Electron and I haven't modified:
{
"name": "app",
"productName": "App",
"version": "0.0.0",
"description": "",
"license": "MIT",
"repository": "user/repo",
"author": {
"name": "",
"email": "",
"url": ""
},
"scripts": {
"test": "xo",
"start": "electron .",
"build": "electron-packager . --out=dist --asar --overwrite --all"
},
"files": [
"index.js",
"index.html",
"index.css"
],
"keywords": [
"electron-app",
"electron"
],
"dependencies": {
"electron-debug": "^1.0.0"
},
"devDependencies": {
"devtron": "^1.1.0",
"electron-packager": "^8.0.0",
"electron": "^1.0.1",
"xo": "^0.16.0"
},
"xo": {
"esnext": true,
"envs": [
"node",
"browser"
]
}
}
Also this is the package.json of my React Project:
{
"name": "react-mobx",
"version": "0.1.0",
"private": true,
"devDependencies": {
"custom-react-scripts": "0.0.23",
"mobx-react-devtools": "^4.2.11"
},
"dependencies": {
"mobx": "^3.1.4",
"mobx-react": "^4.1.2",
"mobx-react-router": "latest",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-router": "latest"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
Note that the React App is fully functional if I don't make use of Electron.
That's why I ask for your wisdom, mates. I need some light here so I can keep moving on with this project. Hope you can help me with this issue and I've provided you with enough information. If you need more info, just let me know.
Warm regards,
Alex.
I'm no React hero (by a long chalk) but I am able to run, hot reload and release build using the schema set out by this boilerplate: electron-es6-react. I added some conditional code to main.js (below) for builds. There are no doubt much better solutions.
You definitely need to merge your React package.json with Electron's.
var isDev = process.env.APP_DEV ? (process.env.APP_DEV.trim() == "true") : false;
if (isDev) {
// only add this during development
require('electron-reload')(__dirname, {
electron: path.join(__dirname, 'node_modules', '.bin', 'electron')
});
}
package.json
{
"name": "electron-es6-react",
"version": "0.1.0",
"description": "template",
"license": "MIT",
"production": false,
"version-string": {
"CompanyName": "Cool Co.",
"FileDescription": "template",
"OriginalFilename": "template",
"ProductName": "template",
"InternalName": "template"
},
"main": "main.js",
"scripts": {
"start": "APP_DEV=true electron -r babel-register .",
"package-mac": "electron-packager . --overwrite --tmpdir=false --platform=darwin --arch=x64 --prune=true --out=release-builds",
"package-win": "electron-packager . --overwrite --tmpdir=false --asar=true --platform=win32 --arch=ia32 --prune=true --out=release-builds"
},
"dependencies": {
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-register": "^6.3.13",
"fs-jetpack": "^0.12.0",
"react": "^15.3.2",
"react-dom": "^15.3.2",
"react-images": "^0.5.2"
},
"devDependencies": {
"electron": "^1.4.3",
"electron-packager": "^8.5.2",
"electron-reload": "^1.1.0"
}
}
Let's say you have a npm project with the following package.json:
{
"name": "XXX",
"version": "YYY",
"license": "ZZZ",
"scripts": {
"scriptA": "...",
"scriptB": "...",
"preinstall": "...",
"postinstall": "..."
},
"devDependencies": {
"depA": "vA",
"depB": "vB"
},
"dependencies": {
"depC": "vC",
"depD": "vD"
}
}
When packing/publishing your package, you don't need the scripts or devDependencies keys. But more dangerously, the preinstall and postinstall scripts could trigger weird/unwanted actions when people install your package as a dependency.
So how do you clean your package.json, ie remove the keys that you don't need?
I'm currently using npm 3.10. If I use the npm pack command, according to the npm documentation it will simply pack the current package if no arguments are provided (therefore taking the raw package.json from disk) and there is no options I can provide to clean it up.
I can of course write my own scripts that would zip the package and generate my own package.json. Is it the way to go?
I have created clean-package to do this.
The most simple usage is just three steps:
npm install clean-package --save-dev
Hook clean-package into the prepack and postpack scripts
"scripts": {
"prepack": "clean-package",
"postpack": "clean-package restore"
}
Configure clean-package as root property in your package.json
"clean-package": {
"remove": [
"script",
"devDependencies",
"preinstall",
"postinstall",
]
}
There are many more options and extended uses, so there is more information on the repo: https://github.com/roydukkey/clean-package.
Using npm itself, this does not seem possible. As of npm 3.10, npm publish or npm pack will indeed just include a pure copy of your package.json in your tgz.
The solution is therefore to generate its own packaged file to have full control over the included package.json.
Basic example
Note: this is using the shell and synchronous method from npm fs
const fs = require('fs');
const os = require('os');
const shell = require('shelljs');
const targz = require('tar.gz');
// create temp directory
const tempDirectory = fs.mkdtempSync(`${os.tmpdir()}/your-project-tarball-`);
const packageDirectory = `${tempDirectory}/package`;
// create subfolder package
fs.mkdirSync(packageDirectory);
// read existing package.json
const packageJSON = require('./package.json');
// copy all necessary files
// https://docs.npmjs.com/files/package.json#files
shell.cp('-R', packageJSON.files, packageDirectory);
shell.cp('-R', ['README.md', 'CHANGELOG.md', 'LICENSE'], packageDirectory);
// create your own package.json or modify it here
Reflect.deleteProperty(packageJSON, 'scripts');
fs.writeFileSync(`${packageDirectory}/package.json`, JSON.stringify(packageJSON, null, 2));
// create tgz and put it in dist folder
targz().compress(packageDirectory, 'your-package.tgz');
Real life example with Lodash
This is for example what the lodash lib does in version 4.17.2. Their original package.json looks like (cf https://github.com/lodash/lodash/blob/4.17.2/package.json):
{
"name": "lodash",
"version": "4.17.2",
"license": "MIT",
"private": true,
"main": "lodash.js",
"engines": { "node": ">=4.0.0" },
"scripts": {
"build": "npm run build:main && npm run build:fp",
"build:fp": "node lib/fp/build-dist.js",
"build:fp-modules": "node lib/fp/build-modules.js",
"build:main": "node lib/main/build-dist.js",
"build:main-modules": "node lib/main/build-modules.js",
"doc": "node lib/main/build-doc github && npm run test:doc",
"doc:fp": "node lib/fp/build-doc",
"doc:site": "node lib/main/build-doc site",
"doc:sitehtml": "optional-dev-dependency marky-markdown#^9.0.1 && npm run doc:site && node lib/main/build-site",
"pretest": "npm run build",
"style": "npm run style:main && npm run style:fp && npm run style:perf && npm run style:test",
"style:fp": "jscs fp/*.js lib/**/*.js",
"style:main": "jscs lodash.js",
"style:perf": "jscs perf/*.js perf/**/*.js",
"style:test": "jscs test/*.js test/**/*.js",
"test": "npm run test:main && npm run test:fp",
"test:doc": "markdown-doctest doc/*.md",
"test:fp": "node test/test-fp",
"test:main": "node test/test",
"validate": "npm run style && npm run test"
},
"devDependencies": {
"async": "^2.1.2",
"benchmark": "^2.1.2",
"chalk": "^1.1.3",
"cheerio": "^0.22.0",
"codecov.io": "~0.1.6",
"coveralls": "^2.11.15",
"curl-amd": "~0.8.12",
"docdown": "~0.7.1",
"dojo": "^1.11.2",
"ecstatic": "^2.1.0",
"fs-extra": "~1.0.0",
"glob": "^7.1.1",
"istanbul": "0.4.5",
"jquery": "^3.1.1",
"jscs": "^3.0.7",
"lodash": "4.17.1",
"lodash-doc-globals": "^0.1.1",
"markdown-doctest": "^0.9.0",
"optional-dev-dependency": "^2.0.0",
"platform": "^1.3.3",
"qunit-extras": "^3.0.0",
"qunitjs": "^2.0.1",
"request": "^2.78.0",
"requirejs": "^2.3.2",
"sauce-tunnel": "^2.5.0",
"uglify-js": "2.7.4",
"webpack": "^1.13.3"
},
"greenkeeper": {
"ignore": [
"lodash"
]
}
}
But the published package.json looks like (cf https://unpkg.com/lodash#4.17.2/package.json)
{
"name": "lodash",
"version": "4.17.2",
"description": "Lodash modular utilities.",
"keywords": "modules, stdlib, util",
"homepage": "https://lodash.com/",
"repository": "lodash/lodash",
"icon": "https://lodash.com/icon.svg",
"license": "MIT",
"main": "lodash.js",
"author": "John-David Dalton <john.david.dalton#gmail.com> (http://allyoucanleet.com/)",
"contributors": [
"John-David Dalton <john.david.dalton#gmail.com> (http://allyoucanleet.com/)",
"Mathias Bynens <mathias#qiwi.be> (https://mathiasbynens.be/)"
],
"scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" }
}
where you can see the scripts and devDependencies keys for example are not there anymore. This is done using a JavaScript Template package.jst as long as a nodejs script Lodash CLI