How to import extension along with files in visual studio code? - javascript

Development using nodejs for running (--experimental-modules)
Current visual studio code intelligence import as below
import config from "./config";
but required as below
import config from "./config.js";
Without .js getting error as below
internal/modules/esm/resolve.js:61
let url = moduleWrapResolve(specifier, parentURL);
^
Error: Cannot find module C:\Uday\Projects\practice-server\config imported from C:\Uday\Projects\practice-server\index.js
at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:61:13)
at Loader.resolve (internal/modules/esm/loader.js:85:40)
at Loader.getModuleJob (internal/modules/esm/loader.js:191:28)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
at link (internal/modules/esm/module_job.js:41:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
So i need visual studio code intelligence for importing with extension??
//index.js
import express from "express";
import config from "./config.js";
const api_app = express();
const api_port = config.api_port
api_app.listen(api_port, () => {
console.log(`Practice Server started on ${api_port}`);
});
//package.json
{
"name": "practice-server",
"type": "module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
//config.js
let config = function () { };
config.api_port = 6000;
export default config;

In the global settings (or the project settings), add the following configuration:
// Preferred path ending for auto imports.
// - auto: Use project settings to select a default.
// - minimal: Shorten `./component/index.js` to `./component`.
// - index: Shorten `./component/index.js` to `./component/index`
// - js: Do not shorten path endings; include the `.js` extension.
"javascript.preferences.importModuleSpecifierEnding": "js",
Note that at the moment this only works for auto imports (i.e via intellisense when referencing an export of another file and VSCode imports it automatically). It does not work with with autosuggest when typing the import statement manually.

I always used my config.js like this this. May be it can help you.
const config = require('./config');
//Now access value from config
const sys_dbconfig = config_data['sys_database'];
const user = configdata['system_admin_name'];
Here is my config.js
var config = {
"sys_database": {
"user": 'postgres',
"host": 'localhost',
"database": 'postgres',
"password": 'postgres',
"port": "5432"
},
"system_admin_name": "system",
"url":"http://xxx.xx.x.xxx:3000/wscalc1?wsdl"
}
module.exports = config;

Related

Uncaught SyntaxError: Cannot use import statement outside a module when import custom lib in google chrome extension

I am create a javascript lib and tried to import into my project, I tried to added dependencies into the google chrome extension code like this in the package.json:
"js-wheel": "git+https://github.com/jiangxiaoqiang/js-wheel.git",
and import modual in the google chrome extension project like this:
import { Auth,Validate } from "js-wheel";
when I run this code, the console shows error like this:
Uncaught SyntaxError: Cannot use import statement outside a module
this is the js-wheel package.json:
{
"name": "js-wheel",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/jiangxiaoqiang/js-wheel.git"
},
"author": "jiangtingqiang#gmail.com",
"license": "ISC",
"bugs": {
"url": "https://github.com/jiangxiaoqiang/js-wheel/issues"
},
"homepage": "https://github.com/jiangxiaoqiang/js-wheel#readme"
}
I have already tried to define the js-wheel to module, why still shows this error? where am I doing wrong? what should I do to fix this problem? In the public lib, I define the index.js like this:
import BaseMethods from "./src/utils/data/checker";
import Validate from "./src/utils/data/validate";
import Auth from "./src/auth/extension/auth";
export default {
BaseMethods,
Validate,
Auth
}
and define the export function like this way:
const Validate = {
mobileCheck: (mobile) => {
let reg = /^[1][3,4,5,7,8][0-9]{9}$/
return reg.test(mobile)
}
}
export default Validate
I searched from intenet and tell me to tweak the package.json type to module, but still not fix this problem. I found the error was throw in the js-wheel internal from this line:
import BaseMethods from "./src/utils/data/checker";
why could not using this way to import in the js-wheel ?

Electron-Prisma Error: can not find module '.prisma/client'

I'm building a Nuxt-electron-prisma app and I kinda stuck here. when I use prisma normally as guided every thing is fine on dev but on build i get this error :
A javascript error occurred in the main process
Uncaught exception:
Error: can not find module : '.prisma/client'
I tried changing prisma provider output to ../resources/prisma/client
generator client {
provider = "prisma-client-js"
output = "../resources/prisma/client"
}
and in main.js of electron
const { PrismaClient } = require('../resources/prisma/client');
const prisma = new PrismaClient()
but I get error Cannot find module '_http_common' at webpackMissingModules in both dev and build ! which by others opinion is caused when using prisma on client-side but I only use it on background.js (main.js of the my boilerplate)
I'm using Nuxtron boilerplate for Nuxt-electron which is using yml file for electron-builder config file and in it I also added prisma to files property:
appId: com.example.app
productName: nuxt-electron-prisma
copyright: Copyright © 2021
nsis:
oneClick: false
perMachine: true
allowToChangeInstallationDirectory: true
directories:
output: dist
buildResources: resources
files:
- "resources/prisma/database.db"
- "node_modules/.prisma/**"
- "node_modules/#prisma/client/**"
- from: .
filter:
- package.json
- app
publish: null
and still get errors
in my win-unpacked/resources I have this only: win-unpacked\resources\app.asar.unpacked\node_modules\#prisma\engines
and of course my package.json
{
"private": true,
"name": "nuxt-electron-prisma",
"productName": "nuxt-electron-prisma",
"description": "",
"version": "1.0.0",
"author": "",
"main": "app/background.js",
"scripts": {
"dev": "nuxtron",
"build": "nuxtron build"
},
"dependencies": {
"electron-serve": "^1.0.0",
"electron-store": "^6.0.1",
"#prisma/client": "^3.0.2"
},
"devDependencies": {
"#mdi/font": "^6.1.95",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/device": "^2.1.0",
"#nuxtjs/dotenv": "^1.4.1",
"#nuxtjs/vuetify": "1.12.1",
"core-js": "^3.15.1",
"electron": "^10.1.5",
"electron-builder": "^22.9.1",
"glob": "^7.1.7",
"noty": "^3.2.0-beta",
"nuxt": "^2.15.7",
"nuxtron": "^0.3.1",
"sass": "1.32.13",
"swiper": "^5.4.5",
"prisma": "^3.0.2",
"vue-awesome-swiper": "^4.1.1"
}
}
The solution provided by Mojtaba Barari works but it results in #prisma packages being present in both resources/app/node_modules and resources/node_modules.
There is a better way how to do it:
{
"build": {
"extraResources": [
{
"from": "node_modules/.prisma/client/",
"to": "app/node_modules/.prisma/client/"
}
],
}
}
In this case, the Prisma client files will be copied directly to resources/app/node_modules where other #prisma packages are already present and so you will save ~ 10 MB compared to the other solution.
EDIT:
My previous solution doesn't work if an application is packaged into an asar archive. You need to use files field instead:
{
"build": {
"files": [
{
"from": "node_modules/.prisma/client/",
"to": "node_modules/.prisma/client/"
}
],
}
}
This is a universal solution which works even if you don't use an asar archive.
Ok, I finally solved it!!
first of all no need to change client generator output direction!
//schema.prisma
datasource db {
provider = "sqlite"
url = "file:../resources/database.db"
}
generator client {
provider = "prisma-client-js"
// output = "../resources/prisma/client" !! no need for this!
}
then in electron-builder config add ./prisma , #prisma and database
// my config file was a .yml
extraResources:
- "resources/database.db"
- "node_modules/.prisma/**/*"
- "node_modules/#prisma/client/**/*"
// or in js
extraResources:[
"resources/database.db"
"node_modules/.prisma/**/*"
"node_modules/#prisma/client/**/*"
]
this solved `Error: cannot find module : '.prisma/client'
but this alone won't read DB in built exe file!
so in main.js where importing #prisma/client should change DB reading directory:
import { join } from 'path';
const isProd = process.env.NODE_ENV === 'production';
import { PrismaClient } from '#prisma/client';
const prisma = new PrismaClient({
datasources: {
db: {
url: `file:${isProd ? join(process.resourcesPath, 'resources/database.db') : join(__dirname, '../resources/database.db')}`,
},
},
})
with these configs I could fetch data from my sqlite DB

Importing git npm modules results in undefined

I have made a npm module in a private git repo and I'm trying to access it in another application.
I'm using reactjs, webpack and npm
So I have the module:
dist
src
| form-mapper
| formMapper.js
| myfile.js
| index.js
package.json
webpack.config.js
Webpack.config.js is like this:
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js'
}
}
Package.json is like this:
{
"name": "my-awesome-module",
"version": "1.0.0",
"license": "ISC",
"main": "./dist/bundle.js",
"scripts": {
"prepare": "npm run build",
"build": "webpack --mode production",
"start": "webpack-dev-server --open --mode development"
},
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^4.3.0",
"webpack-dev-server": "^3.11.0"
}
}
formMapper.js as 2 functions that I'm trying to export:
export function mapForm() {
// some code
}
export function mapUiFormToBackEnd() {
// some code
}
And index.js:
import * as FormMapper from './form-mapper/formMapper'
export { mapForm, mapUiFormToBackEnd } from './form-mapper/formMapper'
export default FormMapper
I've tried a lot of things in index.js so I let everything here just to show you guys what I've already tried.
In my app that needs to use this module I import the module using npm (git+ssh://...) which is working since I can see my module inside node_modules.
When I try to import using:
import FormMapper from 'my-awesome-module'
componentDidMount() {
FormMapper.mapForm()
}
I have this error:
my-awesome-module__WEBPACK_IMPORTED_MODULE_2___default.a.mapForm is not a function
That's my first time trying to create my own npm module and I clearly don't understand everything. I tried several guide but it seems I'm not abla to make it right.
Thanks for the help.
Edit:
When I log my import in my application
import FormMapper from 'my-awesome-module'
componentDidMount() {
console.log(FormMapper)
FormMapper.mapForm()
}
I see an empty object {} getting logged
update your formMapper.js in a more proper way
const mapForm = () => {
// Code here
}
const mapUiFormToBackEnd = () => {
// Code here
}
module.exports = {mapForm, mapUiFormToBackEnd }
on your index.js
// If you just want the mapForm and mapUiFormToBackEnd
const {mapForm, mapUiFormToBackEnd} = require('./form-mapper/formMapper');
// Or if you just want to get all it's fucntion just import it like this
const FormMapper = require('./form-mapper/formMapper') // No need for *
// export the whole FormMapper
module.exports = FormMapper;
// If you want to export a specific functions inside FormMapper
module.exports = {mapForm, mapUiFormToBackEnd }

Running into error when trying to run npm run dev command

I'm trying to follow a tutorial non javascript, so I'm trying to run webpack from node script but I've been getting this weird error, I've searched online but couldn't find the solution
the error:
C:\Users\Ahmad Usman\Desktop\9-forkify\webpack.config.js:2
const path = require("path");
^
below is the code (they are in different files though)
// INDEX.JS FIle
import num from "./test";
console.log(`num: ${num}`);
// TEST.JS FILE
console.log('imported module');
export default 23;
// PACKAGE.JSON
{
"name": "forkify",
"version": "1.0.0",
"description": "forkify project",
"main": "index.js",
"scripts": {
"dev": "webpack"
},
"author": "Ahmad Usman",
"license": "ISC",
"devDependencies": {
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12"
}
}
//WEBPACK.CONFIG.JS
const path = require("path");
const path = require("path");
module.exports = {
entry: "./src/js/index.js",
output: {
path: path.resolve(__dirname, "dist/js"),
filename: "bundle.js",
},
mode: "development",
};
and here is a screenshot of my command line interface
commandline screenshot1
and commandline screenshot2
Thanks
The error says :
SyntaxError: identifier 'path' has already been declared
So if you remove duplicate code it should work:
//WEBPACK.CONFIG.JS
const path = require("path");
const path = require("path"); <-- declared twice
module.exports = {
entry: "./src/js/index.js",
output: {

Running react with webpack dev server, using babel as loader

My index.js keeps getting the parse exception on the first simple HTML element.
I have tried to follow a lot of posts and tried to change between different way of configuration but I keep getting this error. I tried using babel as loader or babel-loader but still no use.
My node module has the required dependencies so nothing seems to be missing. What I am doing wrong here, can anyone point out.
Error
ERROR in ./app/index.js Module parse failed: /mnt/c/development_box/react_sandbox/app/index.js Unexpected token (8:3) You may need an appropriate loader to handle this file type. SyntaxError: Unexpected token (8:3)
at Parser.pp$4.raise (/mnt/c/development_box/react_sandbox/node_modules/webpack/node_modules/acorn/dist/acorn.js:2221:15)
at Parser.pp.unexpected (/mnt/c/development_box/react_sandbox/node_modules/webpack/node_modules/acorn/dist/acorn.js:603:10)
at Parser.pp$3.parseExprAtom (/mnt/c/development_box/react_sandbox/node_modules/webpack/node_modules/acorn/dist/acorn.js:1822:12)
at Parser.pp$3.parseExprSubscripts (/mnt/c/development_box/react_sandbox/node_modules/webpack/node_modules/acorn/dist/acorn.js:1715:21)
at Parser.pp$3.parseMaybeUnary (/mnt/c/development_box/react_sandbox/node_modules/webpack/node_modules/acorn/dist/acorn.js:1692:19)
at Parser.pp$3.parseExprOps (/mnt/c/development_box/react_sandbox/node_modules/webpack/node_modules/acorn/dist/acorn.js:1637:21)
at Parser.pp$3.parseMaybeConditional (/mnt/c/development_box/react_sandbox/node_modules/webpack/node_modules/acorn/dist/acorn.js:1620:21)
at Parser.pp$3.parseMaybeAssign (/mnt/c/development_box/react_sandbox/node_modules/webpack/node_modules/acorn/dist/acorn.js:1597:21)
at Parser.pp$3.parseParenAndDistinguishExpression (/mnt/c/development_box/react_sandbox/node_modules/webpack/node_modules/acorn/dist/acorn.js:1861:32)
at Parser.pp$3.parseExprAtom (/mnt/c/development_box/react_sandbox/node_modules/webpack/node_modules/acorn/dist/acorn.js:1796:19)
at Parser.pp$3.parseExprSubscripts (/mnt/c/development_box/react_sandbox/node_modules/webpack/node_modules/acorn/dist/acorn.js:1715:21) # multi main
here are my files and configurations
package.json
{
"name": "react_sandbox",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server"
},
"author": "",
"license": "BSD-2-Clause",
"dependencies": {
"webpack": "~1.14.0",
"babel-core": "~6.21.0",
"babel-loader": "~6.2.10",
"babel-preset-es2015": "~6.18.0",
"babel-preset-react": "~6.16.0",
"react": "~15.4.1",
"react-dom": "~15.4.1"
},
"devDependencies": {
"webpack-dev-server": "~1.16.2"
}
}
webpack.config.js
var webpack = require('webpack')
var path = require('path')
var BUILD_DIR = path.resolve(__dirname + '/build')
var APP_DIR = path.resolve(__dirname + '/app')
var config =
{
entry : APP_DIR + '/index.js',
output :
{
path : BUILD_DIR,
filename : 'bundle.js',
publicPath : '/'
},
devtool : 'source-map',
devServer :
{
inline : 'true',
contentBase : BUILD_DIR,
port : 3333
},
module :
{
loader :
[
{
test : /\.js?/,
include : APP_DIR,
loader : 'babel',
query :
{
presets : [ 'es2015', 'react' ]
}
}
]
}
}
module.exports = config
index.js
import React from 'react'
import {render} from 'react-dom'
import ReactDOM from 'react-dom'
class App extends React.Component {
render(){
return (
<p>Hello World!</p>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
command
npm run dev

Categories