How to correctly bundle a vscode extension using webpack - visual-studio-code

The problem that i am having is that when i run vsce package i still get the This extension consists of 3587 separate files. For performance reasons, you should bundle your extension: warning, i followed the Bundling Extension steps, debugging works as expected.
package.json
{
"main": "./out/extension",
"scripts": {
"vscode:prepublish": "webpack --mode production",
"webpack": "webpack --mode development",
"webpack-dev": "webpack --mode development --watch",
"compile": "npm run webpack",
"watch": "tsc -watch -p ./",
"postinstall": "node ./node_modules/vscode/bin/install"
},
}
The webpack config is an exact copy of the Bundling Extension example.

This sounds like you might've forgotten to add the source directories to .vscodeignore, so they're still being packaged into the release. The ignore file should probably contain at least the following, plus anything else not needed at runtime:
src/**
node_modules/**

If you are working with a Language Server extension which has both client and server folders, If you exclude the node_modules of the client and server from the bundle the extension would fail when installed and launch for the first time
.vscodeignore contains
.vscode
**/*.ts
**/*.map
out/**
node_modules/**
test_files/**
client/src/**
server/src/**
tsconfig.json
webpack.config.js
.gitignore
Also the documentation is a bit obsolete regarding the webpack.config.js, you have to wrap the 'use strict' into a function with all the settings.
The entry setting was changed according to my needs
//#ts-check
(function () {
'use strict';
const path = require('path');
/**#type {import('webpack').Configuration}*/
const config = {
target: 'node', // vscode extensions run in a Node.js-context 📖 -> https://webpack.js.org/configuration/node/
entry: './client/src/extension.ts', // the entry point of this extension, 📖 -> https://webpack.js.org/configuration/entry-context/
output: {
// the bundle is stored in the 'dist' folder (check package.json), 📖 -> https://webpack.js.org/configuration/output/
path: path.resolve(__dirname, 'dist'),
filename: 'extension.js',
clean: true, //clean the dist folder for each time webpack is run
libraryTarget: 'commonjs2',
devtoolModuleFilenameTemplate: '../[resource-path]'
},
devtool: 'source-map',
externals: {
vscode: 'commonjs vscode' // the vscode-module is created on-the-fly and must be excluded. Add other modules that cannot be webpack'ed, 📖 -> https://webpack.js.org/configuration/externals/
},
resolve: {
// support reading TypeScript and JavaScript files, 📖 -> https://github.com/TypeStrong/ts-loader
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader'
}
]
}
]
}
};
module.exports = config;
}());

Related

Getting this error with the #metaplex-foundation/js-next SDK

Currently working on a react app and I'm getting this error after installing metaplex.
My react-scripts version is 4.0.3
./node_modules/#metaplex-foundation/js-next/dist/esm/programs/token/gpaBuilders/TokenGpaBuilder.mjs
Can't import the named export 'ACCOUNT_SIZE' from non EcmaScript module (only default export is available)
I found out the solution in the git of metaplex here. I will leave you here the whole answer anyway.
Getting Started with Metaplex and CRA 5
This example sets up a new React app with Metaplex using "Create React App" (CRA) version 5 — i.e. using Webpack 5.
This example has been generated using the following steps:
Create a new project using the "Create React App" command.
npx create-react-app getting-started-react-cra5
cd getting-started-react-cra5
Install the Metaplex and the Solana SDKs.
npm install #metaplex-foundation/js #solana/web3.js
Install some polyfills.
npm install assert util crypto-browserify stream-browserify
Install and use react-app-rewired.
# Installs react-app-rewired.
npm install react-app-rewired
# Replaces "react-scripts" with "react-app-rewired" in package.json scripts.
sed -i '' 's/react-scripts /react-app-rewired /g' package.json
Override Webpack 5 configurations.
Create a new file to override Webpack 5 configurations.
touch config-overrides.js
Copy the following code inside the new config-overrides.js file.
const webpack = require("webpack");
module.exports = function override(webpackConfig) {
// Disable resolving ESM paths as fully specified.
// See: https://github.com/webpack/webpack/issues/11467#issuecomment-691873586
webpackConfig.module.rules.push({
test: /\.m?js/,
resolve: {
fullySpecified: false,
},
});
// Ignore source map warnings from node_modules.
// See: https://github.com/facebook/create-react-app/pull/11752
webpackConfig.ignoreWarnings = [/Failed to parse source map/];
// Polyfill Buffer.
webpackConfig.plugins.push(
new webpack.ProvidePlugin({ Buffer: ["buffer", "Buffer"] })
);
// Polyfill other modules.
webpackConfig.resolve.fallback = {
crypto: require.resolve("crypto-browserify"),
stream: require.resolve("stream-browserify"),
util: require.resolve("util"),
assert: require.resolve("assert"),
fs: false,
process: false,
path: false,
zlib: false,
};
return webpackConfig;
};
Update your browser requirements.
Update the browserslist object of your package.json to include the following production requirements.
"browserslist": {
"production": [
- ">0.2%",
- "not dead",
- "not op_mini all"
+ "chrome >= 67",
+ "edge >= 79",
+ "firefox >= 68",
+ "opera >= 54",
+ "safari >= 14"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
That's it!
You should not use #metaplex-foundation/js-next SDK, the actual repo is #metaplex-foundation/js, the name was changed and the updated repo is this, so try using #metaplex-foundation/js instead

How to fix: "The asset path must start with the project source root"?

We have an nrwl/nx project, that we can build on Windows, but it fails on Linux (Ci sytem).
The error is:
The /root/dev/apps/dmc-svr/src/assets asset path must start with the project source root: apps\dmc-svr\src
It seems to be a Windows/Linux path issue
The problem was a Windows like path for the sourceRoot property in project.json
{
"sourceRoot": "apps\\dmc-svr\\src",
"targets": {
"build": {
"executor": "#nrwl/node:build",
"options": {
"assets": [
"apps/dmc-svr/src/assets",
]
}
}
}
}
the fix is to simply replace the backslash \\ with a slash \: sourceRoot": "apps/dmc-svr/src"
We guess that this has been generated by some nx-schema.

Jest: Cannot use import statement outside a module

I got an error when I run test using Jest, I tried to fix this error for 2 hours. But, I couldn't fix it. My module is using gapi-script package and error is occurred in this package. However, I don't know why this is occurred and how to fix it.
jest.config.js
module.exports = {
"collectCoverage": true,
"rootDir": "./",
"testRegex": "__tests__/.+\\.test\\.js",
"transform": {
'^.+\\.js?$': "babel-jest"
},
"moduleFileExtensions": ["js"],
"moduleDirectories": [
"node_modules",
"lib"
]
}
babel.config.js
module.exports = {
presets: [
'#babel/preset-env',
]
};
methods.test.js
import methods, { typeToActions } from '../lib/methods';
methods.js
import { gapi } from "gapi-script";
...
Error Message
C:\haram\github\react-youtube-data-api\node_modules\gapi-script\index.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import
{ gapi, gapiComplete } from './gapiScript';
SyntaxError: Cannot use import statement outside a module
What is wrong with my setting?
As of this writing, Jest is in the process of providing support for ES6 modules. You can track the progress here:
https://jestjs.io/docs/en/ecmascript-modules
For now, you can eliminate this error by running this command:
node --experimental-vm-modules node_modules/.bin/jest
instead of simply:
jest
Be sure to check the link before using this solution.
I solved this with the help of Paulo Coghi's answer to another question -
Does Jest support ES6 import/export?
Step 1:
Add your test environment to .babelrc in the root of your project:
{
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Step 2:
Install the ECMAScript 6 transform plugin:
npm install --save-dev #babel/plugin-transform-modules-commonjs
Jest needs babel to work with modules.
For the testing alone, you do not need jest.config.js, just name the testfiles xxx.spec.js or xxx.test.js or put the files in a folder named test.
I use this babel.config.js:
module.exports = function (api) {
api.cache(true)
const presets = [
"#babel/preset-env"
]
return {
presets
}
}
Adding "type": "module" in package.json or using mjs as stated in other answers is not necessary when your setup is not too complicated.
I have also faced the same issue and this was resolved by adding following command-line option as a environment variable.
export NODE_OPTIONS=--experimental-vm-modules npx jest //linux
setx NODE_OPTIONS "--experimental-vm-modules npx jest" //windows
Upgrading Jest (package.json) to version 29 (latest as of now) solved this problem for me.

How to run jsdoc on directory ignore .gitignore files

I can run jsdoc on a whole project with
$ jsdoc -r .
However this generates docs for js files inside node_modules. How can I tell jsdoc not run on files in .gitignore?
How about using a config file such as this one?
$ jsdoc.js -c ./.jsdoc.conf.json
./.jsdoc.conf.json
{
"source": {
"include": ["."],
"includePattern": ".+\\.js(doc|x)?$",
"excludePattern": "node_modules"
}
}
Borrowed from Generate jsdoc documentation here on Stack.
{
"source": {
"include": ["."],
"includePattern": ".(jsx|js|ts|tsx)$",
"exclude": [
"node_modules",
"docs"
]
}
}

Karma preprocessor not running

My karma.conf.js includes:
plugins: [
'karma-jasmine',
'karma-phantomjs-launcher',
'karma-ng-html2js-preprocessor'
],
preprocessors: {
'../../mypath/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
moduleName: 'templates'
},
(I've tried without specifying any plugins, too.)
My devDependencies include:
"karma-ng-html2js-preprocessor": "^0.2.0"`
My tests include:
beforeEach(module('templates'));
These give the error:
Module 'templates' is not available!
Running karma with --log-level debug, I do not see any [preprocessor.html2js] entries. (I do get Loading plugin karma-ng-html2js-preprocessor.)
What am I doing wrong?
The issues were that the templates must be listed under files as well, and that the glob pattern in preprocessors must match. This is implied by the documentation.
files: [
'../../Scripts/angular-app/directives/*.html',
// .js files
],
preprocessors: {
'../../Scripts/angular-app/**/*.html': ['ng-html2js']
},
Note that **/*.html does not match parent directories of the basePath.
karma start --log-level debug will display DEBUG [preprocessor.html2js] entries when everything is correct.
I was also able to remove the plugins section.
To get the correct cache ID, I used:
ngHtml2JsPreprocessor: {
// Load this module in your tests of directives that have a templateUrl.
moduleName: 'templates',
cacheIdFromPath: function (filepath) {
return filepath.substring(filepath.indexOf('/Scripts/angular-app/'));
}
},
If a template references a custom filter, the filter must be loaded in files and the filter's module must be loaded in your directive tests.