I'm trying to create VS Code extension. It works when fine when I develop, however when I create the package and install it to VS Code it is failing with following error:
ERR Cannot find module 'request': Error: Cannot find module 'request'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:602:15)
at Function.Module._load (internal/modules/cjs/loader.js:528:25)
at Function.t._load (c:\Users\USER\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:729:537)
at Function.t.getExtensionPathIndex.then.a._load (c:\Users\USER\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:691:639)
at Function.t.getExtensionPathIndex.then.r._load (c:\Users\USER\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:655:197)
at Module.require (internal/modules/cjs/loader.js:658:17)
at n (c:\Users\USER\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\loader.js:15:874)
at openBambooPlanUrlInBrowser.GIT.getGitBranchFromFileName (C:\Users\USER\.vscode\extensions\dUSER.markdown-table-of-contents-0.0.1\out\extension.js:397:41)
at getGitBranchFromFileName.exec (C:\Users\USER\.vscode\extensions\dUSER.markdown-table-of-contents-0.0.1\out\extension.js:383:17)
at ChildProcess.exithandler (child_process.js:294:7)
at ChildProcess.emit (events.js:182:13)
at maybeClose (internal/child_process.js:961:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:248:5)
my code:
async openBambooPlanUrlInBrowser(fileName: string) {
new GIT().getGitBranchFromFileName(fileName, (branch: string) => {
var config: any = vscode.workspace.getConfiguration('markdown-table-of-contents').get('bitbucketRepositories');
for (var setting of config) {
if (fileName.toLowerCase().startsWith(setting.folder.toLowerCase())) {
branch = branch.replace('/', '-');
let bambooHost = vscode.workspace.getConfiguration('markdown-table-of-contents').get('atlassianBambooHost');
const request = require('request');
request(
{
url: `${bambooHost}/rest/api/latest/plan/${setting.bambooPlanKey}/branch/${branch}.json`,
headers: {
"Authorization": 'Basic ' + vscode.workspace.getConfiguration('markdown-table-of-contents').get('atlassianAuthHash')
}
},
(error: string, response: string, body: string) => {
let planKey = JSON.parse(body).key;
vscode.env.openExternal(vscode.Uri.parse(`${bambooHost}/browse/${planKey}`));
}
);
}
}
});
}
dependencies from package.json
"dependencies": {
"child_process": "^1.0.2",
"clipboardy": "^1.2.3",
"fs": "0.0.1-security",
"iconv-lite": "^0.4.24",
"path": "^0.12.7",
"request": "^2.88.0",
"util": "^0.11.1",
"xml2js": "^0.4.19",
"xmldom": "^0.1.27"
}
root folder:
.gitignore
.vscode
.vscodeignore
depl.bat
markdown-table-of-contents-0.0.1.vsix
node_modules
out
package-lock.json
package.json
src
tsconfig.json
tslint.json
For me the solution was to run npm install <package_name> (notice no "-g") from the extension's code root folder. Vscode puts the extension in its [extension folder][1], navigate there to do npm install.
Example: for linux/mac
cd ~/.vscode/extensions
cd your.extension
npm install
This automatically added it to the devDependencies as well, and the extension worked perfectly from there on.
Related
I started this Typescript course and the steps to set everything up are quite straightforward. I created a new directory, ran npm init, then npm install --save-dev ts-node typescript. I added a script to my package.json as follows like the course suggests
PACKAGE.JSON:
{
"name": "part9",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"ts-node": "ts-node"
},
"author": "",
"license": "ISC",
"devDependencies": {
"ts-node": "^10.2.1",
"typescript": "^4.3.5"
}
}
and created a multiplier.ts file as follows:
const multiplicator = (a, b, printText) => {
console.log(printText, a * b);
};
multiplicator(2, 4, "Multiplied numbers 2 and 4, the result is:");
at this point, the course says to run the script npm run ts-node -- multiplier.ts but when I do that, my terminal blows up with errors. I spent an hour installing several packages that other stackoverflow users suggested but nothing works and the error message isn't exactly clear what is wrong to a beginner. Can someone help me? This is the error below. I am using Windows 10 if that makes a difference.
> part9#1.0.0 ts-node C:\Users\user\Documents\Documents\Projects\_Courses\FullStackOpen\part9
> ts-node "multiplier.ts"
C:\Users\user\Documents\Documents\Projects\_Courses\FullStackOpen\part9\node_modules\ts-node\src\index.ts:692
return new TSError(diagnosticText, diagnosticCodes);
^
TSError: тип Unable to compile TypeScript:
multiplier.ts:1:24 - error TS7006: Parameter 'a' implicitly has an 'any' type.
1 const multiplicator = (a, b, printText) => {
~
multiplier.ts:1:27 - error TS7006: Parameter 'b' implicitly has an 'any' type.
1 const multiplicator = (a, b, printText) => {
~
multiplier.ts:1:30 - error TS7006: Parameter 'printText' implicitly has an 'any' type.
1 const multiplicator = (a, b, printText) => {
~~~~~~~~~
multiplier.ts:2:3 - error TS2584: Cannot find name 'console'. Do you need to change your target library? Try
changing the 'lib' compiler option to include 'dom'.
2 console.log(printText, a * b);
~~~~~~~
at createTSError (C:\Users\user\Documents\Documents\Projects\_Courses\FullStackOpen\part9\node_modules\ts-node\src\index.ts:692:12)
at reportTSError (C:\Users\user\Documents\Documents\Projects\_Courses\FullStackOpen\part9\node_modules\ts-node\src\index.ts:696:19)
at getOutput (C:\Users\user\Documents\Documents\Projects\_Courses\FullStackOpen\part9\node_modules\ts-node\src\index.ts:883:36)
at Object.compile (C:\Users\user\Documents\Documents\Projects\_Courses\FullStackOpen\part9\node_modules\ts-node\src\index.ts:1185:30)
at Module.m._compile (C:\Users\user\Documents\Documents\Projects\_Courses\FullStackOpen\part9\node_modules\ts-node\src\index.ts:1309:30)
at Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Object.require.extensions.<computed> [as .ts] (C:\Users\user\Documents\Documents\Projects\_Courses\FullStackOpen\part9\node_modules\ts-node\src\index.ts:1313:12)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12) {
diagnosticText: "\x1B[96mmultiplier.ts\x1B[0m:\x1B[93m1\x1B[0m:\x1B[93m24\x1B[0m - \x1B[91merror\x1B[0m\x1B[90m TS7006: \x1B[0mParameter 'a' implicitly has an 'any' type.\r\n" +
'\r\n' +
'\x1B[7m1\x1B[0m const multiplicator = (a, b, printText) => {\r\n' +
'\x1B[7m \x1B[0m \x1B[91m ~\x1B[0m\r\n' +
"\x1B[96mmultiplier.ts\x1B[0m:\x1B[93m1\x1B[0m:\x1B[93m27\x1B[0m - \x1B[91merror\x1B[0m\x1B[90m TS7006: \x1B[0mParameter 'b' implicitly has an 'any' type.\r\n" +
'\r\n' +
'\x1B[7m1\x1B[0m const multiplicator = (a, b, printText) => {\r\n' +
'\x1B[7m \x1B[0m \x1B[91m ~\x1B[0m\r\n' +
"\x1B[96mmultiplier.ts\x1B[0m:\x1B[93m1\x1B[0m:\x1B[93m30\x1B[0m - \x1B[91merror\x1B[0m\x1B[90m TS7006: \x1B[0mParameter 'printText' implicitly has an 'any' type.\r\n" +
'\r\n' +
'\x1B[7m1\x1B[0m const multiplicator = (a, b, printText) => {\r\n' +
'\x1B[7m \x1B[0m \x1B[91m ~~~~~~~~~\x1B[0m\r\n' +
"\x1B[96mmultiplier.ts\x1B[0m:\x1B[93m2\x1B[0m:\x1B[93m3\x1B[0m - \x1B[91merror\x1B[0m\x1B[90m TS2584: \x1B[0mCannot find name 'console'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.\r\n" +
'\r\n' +
'\x1B[7m2\x1B[0m console.log(printText, a * b);\r\n' +
'\x1B[7m \x1B[0m \x1B[91m ~~~~~~~\x1B[0m\r\n',
diagnosticCodes: [ 7006, 7006, 7006, 2584 ]
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! part9#1.0.0 ts-node: `ts-node "multiplier.ts"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the part9#1.0.0 ts-node script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\user\AppData\Roaming\npm-cache\_logs\2021-08-26T00_32_28_752Z-debug.log
Those errors are to be expected with an out of the box TS setup. The error a implicitly has any type means that you haven't given the param a an expected type and it defaults to any.
If you wanted to fix that error you could give the parameters a typing:
const multiplicator = (a: number, b: number, printText: string) => {
console.log(printText, a * b);
};
Or alternatively you could tell typescript you don't mind if you have implicit any types in your tsconfig.json like so:
{
"compilerOptions": {
"noImplicitAny": false
}
}
If you don't have a tsconfig then you should run tsc --init and it'll create a basic one for you.
To fix the error about console being not being found, you need to add the DOM lib to your tsconfig
{
"compilerOptions": {
"lib": ["DOM"]
}
}
This will give you all the global references for a browser environment such as window, etc. If you're just doing this via commandline you can npm install #types/node and that will give you all the node types you need
well you is missing the tsconfig.json let's begin by
init
to create a new project you need
$ npm init
dependencies
then in the folder where yow package.json was added run this
$ npm i -D typescript tslib tsutils ts-node
typescript configuration
now to create a typescript project run this
$ ./node_modules/typescript/bin/tsc --init
tsconfig.json
yow tsconfig.josn is where the configuration of typescript will be learn more here: https://www.typescriptlang.org/tsconfig
start
to run the program in your case would be like this
{
"scripts": {
"start": "ts-node ./path-to-where-yow-file-is"
}
}
You should install this npm pacage.
npm install --save-dev #types/node
And I have changed the file "tsconfig.json", then it will work.
{
"compilerOptions": {
"lib": ["dom"]
}
}
I am using Webpack version 6.14.8 in an Asp.net Core Razor Pages application in Visual Studio 2019. I am trying to create a readable output file. Here is the structure:-
|-->wwwroot
----->src (created manually)
------->index.js (created manually)
|-->dist (generated by webpack)
------->main.js (webpack bundle)
|-->node_modules (npm init webpack --save-dev)
|-->package.json (npm init -y)
----->package-lock.json (npm init -y)
|-->webpack.config.js (manually configured)
The src/index.js file is blank index.js file.
The package.json: -
{
"name": "aspnet.core",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"wbp": "webpack --entry ./src/index.js --output ./dist/main.js --mode development",
"build": "webpack --config webpack.config.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"lodash": "^4.17.20",
"startbootstrap-simple-sidebar": "^5.1.2",
"webpack": "^5.1.3",
"webpack-cli": "^4.0.0"
}
webpack.config.js:
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src') + '/path/to/your/file.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
}
};
I am trying to create a readable output folder: -"dist/main.js" in wwwroot folder: dist/main.js. However, when I ran the command: npm run wbp, I received the following error message about the entry module could not be found: Error: Can't resolve './src/index.js' in C:\ directory folder: -
C:\Users\xxx\Desktop\My Folder\Visual Studio\Projects\Final\HelloWorld >npm run wbp
>helloword#1.0.0 wbp C:\Users\xxx\Desktop\My Folder\Visual Studio\Projects\Final\HelloWorld
>webpack ./src/index.js --output ./dist/main.js --mode development
asset main.js 1.47 KiB [emitted] (name: main)
.dist/main.js 644 bytes built] code generated
ERROR in main
Module not found: Error: Can't resolve './src/index.js' in C:\Users\xxx\Desktop\My Folder\Visual Studio\Projects\Final\HelloWorld
webpack 5.1.3 compiled with 1 error in 858 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! HelloWorld#1.0.0 build: `webpack --config webpack.config.js --mode development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the HelloWorld#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\xxx\AppData\Roaming\npm-cache\_logs\2020-10-18T07_19_13_940Z-debug.log
C:\Users\xxx\Desktop\My Folder\Visual Studio\Projects\Final\HelloWorld >
The dist/main file was created in the project directory and its contents are: -
/*
* ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
* This devtool is not neither made for production nor for readable output files.
* It uses "eval()" calls to create a separate source file in the browser devtools.
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
* or disable the default devtool with "devtool: false".
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
*/
/******/ (() => { // webpackBootstrap
/*!**********************!*\
!*** ./dist/main.js ***!
\**********************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: */
eval("/*\n * ATTENTION: The \"eval\" devtool has been used (maybe by default in mode: \"development\").\n * This devtool is not neither made for production nor for readable output files.\n * It uses \"eval()\" calls to create a separate source file in the browser devtools.\n * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)\n * or disable the default devtool with \"devtool: false\".\n * If you are looking for production-ready output files, see mode: \"production\" (https://webpack.js.org/configuration/mode/).\n */\n/******/ (() => { // webpackBootstrap\n/******/ \t\"use strict\";\n/******/ })()\n;\n\n//# sourceURL=webpack://HelloWorld/./dist/main.js?");
/******/ })()
;
I looked at the url address:- https://webpack.js.org/configuration/devtool/, and I tried the "output.path" option: Output|webpack, but it did not work, when I ran the "npm run wbp" command.
How do I fix the issue of input: .src/index.js file is not found and how do I create a readable output: dist/main file?
Thank you in advance.
Current structure:-
|-->wwwroot
----->src (created manually)
------->index.js (created manually)
----->dist (generated by webpack-created by the command: npm run build)
------->main.js (webpack bundle-created by the command: npm run build)
------->index.html (created by the command: npm run build)
|-->node_modules (npm init webpack --save-dev)
|-->package.json (npm init -y)
----->package-lock.json (npm init -y)
|-->webpack.config.js (manually configured)
package.json
"name": "aspnet.core",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "SET NODE_ENV='production' && webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^5.0.0",
"html-webpack-plugin": "^4.5.0",
"lodash": "^4.17.20",
"popper.js": "^1.16.1",
"startbootstrap-simple-sidebar": "^5.1.2",
"style-loader": "^2.0.0",
"webpack": "^5.1.3",
"webpack-cli": "^4.0.0",
"webpack-node-externals": "^2.5.2"
},
"dependencies": {
"#fullcalendar/core": "^5.3.1",
"#fullcalendar/daygrid": "^5.3.2",
"#fullcalendar/list": "^5.3.1",
"#fullcalendar/timegrid": "^5.3.1"
}
}
I updated the input and output files of the webpack.config.js file in development mode as follows: -
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
module.exports = {
mode: 'development',
entry: [
'babel-polyfill',
'./wwwroot/src/index.js'
],
output: {
path: path.resolve(__dirname, 'wwwroot/dist'),
filename: 'main.js'
},
resolve: {
extensions: ['.js', '.json']
},
module: {
rules: [
{ test: /\.(js)$/, use: { loader: 'babel-loader', options: {presets: ['#babel/preset-react']} }},
{ test: /\.(sass|scsss|css)$/, use: ['style-loader', 'css-loader'] },
{ test: /\.(svg|eot|woff|woff2|ttf)$/, use: ['file-loader'] },
]
},
target: 'node', // in order to ignore built-in modules like path, fs, etc.
externals: [nodeExternals()], //in order to ignore all modules in node_modules folder
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin(),
],
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development'
}
and afterwards run the command:- npm run build
I am following the Set Protocol Getting Started tutorial. I am familiar with vanilla Javascript, but not with Node, NPM, Webpack etc. I picked up bare minimum info on these and have been trying to run the code described in the tutorial in a browser. You can find the latest code in this github repo.
index.html has following code:
<html>
<script src="main.js"></script>
<body>
<div>
Hello World!
</div>
</body>
</html>
package.json looks like this:
{
"dependencies": {
"#0xproject/typescript-typings": "^3.0.2",
"bignumber.js": "^5.0.0",
"setprotocol.js": "^1.2.9-rc1",
"web3": "^1.0.0-beta.36"
},
"name": "setprotocol",
"version": "1.0.0",
"description": "set protocol tutorial",
"author": "swapna",
"license": "MIT",
"private": true,
"devDependencies": {
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12"
}
}
webpack.config.js looks like this:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
node: {
fs: 'empty',
},
optimization: {
minimize: false
},
};
I see bignumber.js under node_modules in the root of my project:
I am building main.js by running npx webpack --config webpack.config.js
When I load index.html in the browser (running npm install http-server -g in the dist folder), I see following error in the browser's JS console:
main.js:203795 Uncaught (in promise) ReferenceError: BigNumber is not defined
at createStableSet (main.js:203795)
at Module.<anonymous> (main.js:203818)
at __webpack_require__ (main.js:20)
at main.js:84
at main.js:87
createStableSet # main.js:203795
(anonymous) # main.js:203818
__webpack_require__ # main.js:20
(anonymous) # main.js:84
(anonymous) # main.js:87
Code where the error happens:
What am I doing wrong? Please help!
In the module where you use BigNumber, you need to import it. Eg, if you have
// mymodule.js
(async () => {
const { units, naturalUnit } = await setProtocol.calculateSetUnitsAsnyc(
componentAddresses,
[new BigNumber(1), new BigNumber(1)],
// ...
Change it to
// mymodule.js
import BigNumber from 'bignumber';
(async () => {
const { units, naturalUnit } = await setProtocol.calculateSetUnitsAsnyc(
componentAddresses,
[new BigNumber(1), new BigNumber(1)],
// ...
Visual Studio task runner cannot load the gulp file. I use VS2017 v15.9.4 now, however, the project developed some years ago.
Failed to run "...\Gulpfile.js"...
cmd.exe /c gulp --tasks-simple
assert.js:350
throw err;
^
AssertionError [ERR_ASSERTION]: Task function must be specified
at Gulp.set [as _setTask] (...\node_modules\undertaker\lib\set-task.js:10:3)
at Gulp.task (...\node_modules\undertaker\lib\task.js:13:8)
at Object.<anonymous> (...\gulpfile.js:34:6)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
I replaced my project local address by "..."
npm -v --> 6.4.1
node -v --> 10.14.2
gulp -v --> CLI version 2.0.1
Local version 4.0.0
The content of package.json file:
{
"version": "1.0.0",
"name": "tratic",
"private": true,
"devDependencies": {
"gulp": "github:gulpjs/gulp#4.0",
"gulp-clean-css": "3.5.0",
"gulp-concat": "2.6.1",
"gulp-durandal": "1.1.7",
"gulp-install": "^1.1.0",
"gulp-uglify": "3.0.0",
"gulp-util": "3.0.8",
"rimraf": "2.6.1"
},
"dependencies": {
"assert": "^1.4.1",
"assert-js": "^0.20.0",
"natives": "^1.1.5"
},
"scripts": {
"gulp": "./node_modules/gulp/bin/gulp.js"
}
}
The content of gulpfile.js:
var gulp = require('gulp'),
durandal = require('gulp-durandal'),
rimraf = require('rimraf');
gulp.task('clean', function (cb) {
rimraf('app/main-built.js', cb);
});
gulp.task('durandal', ['clean'], function () {
durandal({
baseDir: 'app',
main: 'main.js',
output: 'main-built.js',
almond: true,
minify: true
})
.pipe(gulp.dest('app'));
});
gulp.task('default', ['durandal']);
I google it and the existing solutions cannot solve the problem. There are some related issue but does not work for me.
How can I solve the problem?
I have tried your setup, it indeed threw an error like yours.
I went to the gulp docs and tried their version of a gulpfile, and it worked with no issues. So I have rewritten your gulpfile to match their example and it worked well.
here's the code:
var gulp = require('gulp'),
durandal = require('gulp-durandal'),
rimraf = require('rimraf');
var paths = {
app: "./App/**/*.js",
js: "./Scripts/**/*.js",
css: "./Content/**/*.css",
concatJsDest: "./Scripts/vendor-scripts.min.js",
concatCssDest: "./Content/vendor-css.min.css"
};
function clean (cb) {
rimraf('app/main-built.js', cb);
}
gulp.task('clean', clean);
function runDurandal () {
return durandal({
baseDir: 'app',
main: 'main.js',
output: 'main-built.js',
almond: true,
minify: true,
rjsConfigAdapter: function (rjsConfig) {
rjsConfig.deps = ['text'];
return rjsConfig;
}
})
.pipe(gulp.dest('app'));
}
var build = gulp.series(clean, runDurandal);
gulp.task('default', build);
Basically I have moved functions that you use as tasks to variables, and used series to run durandal.
then I have tried npx gulp --tasks-simple
and have a proper output
clean
default
btw, have a look at npx so you don't have to install gulp globally.
Hope that helps!
This syntax is no longer allowed in gulp4:
gulp.task('default', ['durandal']);
Use :
gulp.task('default', gulp.series('durandal'));
Likewise change to:
gulp.task('durandal', gulp.series('clean', function (done) {
durandal({
baseDir: 'app',
main: 'main.js',
output: 'main-built.js',
almond: true,
minify: true
})
.pipe(gulp.dest('app'));
done();
});
Also, using pump would probably give you better error reporting than you are getting without it.
Try to use this workaround: https://github.com/ampproject/docs/issues/793
Downgrade gulp to this version 3.9.1.
I have written a code in node.js(ES6) and below is my problem with steps i followed to run my code:
-Step1:
ES6 code==>(babel)==>successfully transpiled code when run (npm run build)
-Step2:
run command (npm start) throws error "SyntaxError: Unexpected token import"
But if i run "nodemon ./src/index.js --exec babel-node" it runs successfully.
I have also tried to understand the reason for failure by searching similar questions on stackoverflow before posting this question here but not able to make my code work.
I really appreciate your help guys i do not know how to proceed from here, our whole production deployment is stuck due to this issue:(.
Below you will find my code files which shows i have already used babel and .babelrc in my code:
Package.json-
"dependencies": {
"babel-preset-es2015": "^6.24.1",
"body-parser": "^1.16.0",
"connect-timeout": "^1.8.0",
"core-js": "^2.4.1",
"cors": "^2.8.1",
"express": "^4.14.1",
"joi": "^10.2.2",
"jsonapi-serializer": "^3.5.3",
"mongoose": "^4.10.4",
"mongoose-rename-id": "^1.0.2",
"nedb": "^1.8.0",
"path": "^0.12.7",
"randomstring": "^1.1.5",
"request": "^2.79.0",
"request-promise": "^4.1.1",
"swagger-express-mw": "^0.1.0",
"swagger-ui": "^2.2.10",
"yamljs": "^0.2.8"
},
"devDependencies": {
"babel-cli": "^6.22.2",
"babel-core": "^6.22.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2015-node": "^6.1.1",
"babel-preset-es2016-node4": "^6.0.1",
"babel-preset-es2017": "^6.22.0",
"chai": "^3.5.0",
"chai-as-promised": "^6.0.0",
"husky": "^0.13.1",
"mocha": "^3.2.0",
"mocha-duplicate-reporter": "^0.2.1",
"mocha-multi": "^0.9.0",
"mocha-sonar-generic-test-coverage": "0.0.1",
"nock": "^9.0.2",
"node-mocks-http": "^1.6.1",
"nodemon": "^1.11.0",
"nyc": "^10.1.2",
"pact": "^1.0.0",
"rimraf": "^2.5.4",
"sinon": "^1.17.7",
"sinon-chai": "^2.8.0",
"snazzy": "^6.0.0",
"standard": "^8.6.0",
"unit.js": "^2.0.0"
},
.babelrc-
{
"presets": [
"es2016-node4",
"es2017",
"es2015"
]
}
code for index.js:
'use strict'
import * as path from 'path'
import {PORT} from 'config'
// config module loads the configuration from the folder the process is run
process.env[ 'NODE_CONFIG_DIR' ] = path.resolve(__dirname, '/config')
import server from './server'
// Start the server
server(PORT)
code for server.js:
import cors from 'cors'
import SwaggerExpress from 'swagger-express-mw'
import bodyParser from 'body-parser'
import timeout from 'connect-timeout'
import * as YAML from 'yamljs'
import * as path from 'path'
import account from '../src/api/controllers/accounts.js'
const version = {
file: YAML.load(path.join(__dirname, 'version.yml'))
}
var config = {
appRoot: __dirname,
swaggerFile: path.resolve(__dirname, 'api', 'swagger', 'swagger.json'),
basePath: '/api/v1',
swaggerSecurityHandlers:{
basicAuth :async function(req, authOrSecDef, scopesOrApiKey, callback){
try{
//let data = true
console.log(req.headers.authorization)
let data = await account.authenticate(req.headers.authorization)
if(data.statusCode==200){
console.log(data)
callback(null,true);
}
else
callback(new Error("Access denied"))
}catch(err){
callback(new Error("Access denied"))
}
console.log("response ...."+data)
}
}
}
export default function start (serverPort) {
SwaggerExpress.create(config, function (err, swaggerExpress) {
if (err) {
throw err
}
var app = require('express')()
// Hack to override the host and port
app.get(path.resolve(config.basePath, '/api-docs'), function (req, res) {
swaggerExpress.runner.swagger.host = req.get('host')
// Set correct version for the API
swaggerExpress.runner.swagger.info.version = version.file.build.name
res.json(swaggerExpress.runner.swagger)
})
// Customize SwaggerUI
var swaggerUIParams = {
swaggerUi: config.basePath + '/docs',
apiDocs: config.basePath + '/api-docs'
}
// Add for version
app.get('/version', function (req, res) {
// Load yaml file using YAML.load
res.json(version.file.build)
})
// serves the Swagger documents and Swagger UI
app.use(swaggerExpress.runner.swaggerTools.swaggerUi(swaggerUIParams))
app.use(cors())
app.use(bodyParser.json())
app.use(timeout('6s'))
// install middleware
swaggerExpress.register(app)
app.listen(serverPort)
})
}
code for Accounts.js(here it actually throws the error at import statement first line):
import request from 'request-promise'
export default account()
function account() {
return {
authenticate: async function authenticate (authheader) {
console.log("Sending call for Account")
let temp = (authheader).split(" ")
console.log(temp[1])
let buf = new Buffer(temp[1], 'base64'); // create a buffer and tell it the
data coming in is base64
let plain_auth = buf.toString(); // read it back out as a string
console.log("Decoded Authorization ", plain_auth);
const cred = plain_auth.split(':')
const options={
uri: `http://localhost:3000/api/account/${cred[0]}`,
json: true,
resolveWithFullResponse: true,
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Accept': 'application/json; charset=utf-8'
// 'Authorization':authheader
},
method: 'GET'
}
return request(options).then((response) => {
console.log(response.statusCode)
return {
"statusCode":response.statusCode,
"body":response.body
}
}).catch((err) => {
console.log(err);
console.log('errorstatuscode:' + err.statusCode)
});
}
}
}
scripts in package.json:
"scripts": {
"build:transpile": "babel src/ -d dist",
"build:copy-resources": "cp -r config dist && cp -r src/api/swagger dist/api
&& cp src/version.yml dist",
"build": "rimraf dist && npm run build:transpile && npm run build:copy-
resources",
"devstart": "nodemon ./src/index.js --exec babel-node",
"start": "node dist/index.js",
}
Dear all the issue is resolved now, the error is in the path defined at server.js at the below line:
-import account from '../src/api/controllers/accounts.js'
There is no issue with the babel or transpiled code, its due to the wrong path definition which tells the code to pick file accounts.js from src folder not from the transpiled code present in dist folder as a result it failed and throws the error of unexpected token import.
Now i have corrected the relative path and its working fine with npm run start as well.
Thanks you all too for your support.
require babel-register module start of your index.js
require('babel-register');
I think it will solve your problem.
Your npm run build work when you are bundling code, that time babel transpile your code as per your configuration provided to webpack/gulp.
But when you start server then babel does not transpile it because babel does not aware about it.