#rollup/plugin-babel cannot convert Spread operator correct when target is 'es5' - babeljs

Rollup Version
rollup 2.78.0
#rollup/plugin-babel 5.3.1
Operating System (or Browser)
macOS 11.6.7
browser: chrome 107.0.5304.87
Node Version
14.18.0
rollup config
const plugins = [
nodeResolve({
preferBuiltins: false,
modulesOnly: true,
extensions: ['js', '.ts'],
}),
commonjs(),
// json(),
// globals(),
// builtins(),
typescript({
target: 'es5',
declaration: true,
declarationDir: 'dist',
}),
babel({
exclude: 'node_modules/**',
babelHelpers: 'runtime', // 开启体积优化
}),
// others
]
questions
I use Spread to convert a Set variable to Array variable, just like this:
const set = new Set();
const getSet = () => {
return [...set]
}
but I found that this function return [] all the time, so I check the build files, and found the Spread API is converted to Array.prototype.slice:
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
However, Array.prototype.slice cannot handle the Set, or in other word, Array.prototype.slice.call(Set) will return [] all the time, and it works if I set the target to es6.
expect
So, my questions is , how can it work when target is 'es5'? I think maybe I need add some configs, but I can't find a solution in document or other article

Related

Mochawesome with Cypress - how to get aggregated charts at higher level?

I've just started using mochawesome with Cypress (9.7). Our test structure is basically a number of spec files, each following something like the following format:
describe('(A): description of this spec', () => {
describe ('(B): description of test abc', () => {
before(() => {
// do specific set up bits for this test
})
it('(C): runs test abc', () => {
// do actual test stuff
})
})
})
Where within each spec file there would be a single 'A' describe block, but there can be many 'B' level blocks (each with a single 'C') - done this way because the before block for each 'C' is always different - I couldn't use a beforeEach.
When I run my various spec files, each structured similarly to the above, the mochaewsome output is mostly correct - I get a collapsible block for each spec file at level 'A', each with multiple collapsible blocks at level B, each with test info as expected at level C.
But... The circular charts are only displayed at level B. What I was hoping, was that it might be possible to have aggregated charts at level A, and a further aggregated chart for all the level A blocks.
Not sure I've explained this brilliantly(!), but hopefully someone understands, and can offer a suggestion?!
In cypress-mochawesome-reporter there's an alternative setup using on('after:run') which can perform the aggregation.
In Cypress v9.7.0
// cypress/plugins/index.js
const { beforeRunHook, afterRunHook } = require('cypress-mochawesome-reporter/lib');
const { aggregateResults } = require('./aggregate-mochawesome-report-chart');
module.exports = (on, config) => {
on('before:run', async (details) => {
await beforeRunHook(details);
});
on('after:run', async () => {
aggregateResults(config)
await afterRunHook();
});
};
In Cypress v10+
// cypress.config.js
const { defineConfig } = require('cypress');
const { beforeRunHook, afterRunHook } = require('cypress-mochawesome-reporter/lib');
const { aggregateResults } = require('./aggregate-mochawesome-report-chart');
module.exports = defineConfig({
reporter: 'cypress-mochawesome-reporter',
video: false,
retries: 1,
reporterOptions: {
reportDir: 'test-report',
charts: true,
reportPageTitle: 'custom-title',
embeddedScreenshots: true,
inlineAssets: false,
saveAllAttempts: false,
saveJson: true
},
e2e: {
setupNodeEvents(on, config) {
on('before:run', async (details) => {
await beforeRunHook(details);
});
on('after:run', async () => {
aggregateResults(config)
await afterRunHook();
});
},
},
});
The module to do the aggregation is
// aggregate-mochawesome-reporter-chart.js
const path = require('path');
const fs = require('fs-extra')
function aggregateResults(config) {
const jsonPath = path.join(config.reporterOptions.reportDir , '/.jsons', '\mochawesome.json');
const report = fs.readJsonSync(jsonPath)
const topSuite = report.results[0].suites[0]
aggregate(topSuite)
fs.writeJsonSync(jsonPath, report)
}
function aggregate(suite, level = 0) {
const childSuites = suite.suites.map(child => aggregate(child, ++level))
suite.passes = suite.passes.concat(childSuites.map(child => child.passes)).flat()
suite.failures = suite.failures.concat(childSuites.map(child => child.failures)).flat()
suite.pending = suite.pending.concat(childSuites.map(child => child.pending)).flat()
suite.skipped = suite.skipped.concat(childSuites.map(child => child.skipped)).flat()
if (!suite.tests.length && suite.suites[0].tests.length) {
// trigger chart when to describe has no tests
suite.tests = [
{
"title": "Aggregate of tests",
"duration": 20,
"pass": true,
"context": null,
"err": {},
"uuid": "0",
"parentUUID": suite.uuid,
},
]
}
return suite
}
module.exports = {
aggregateResults
}
The function aggregate() recursively loops down through child suites and adds the test results to the parent.
json files
Note the json file is different at the point where afterRunHook runs and at the end of the test run.
If you have the option saveJson: true set, you will get a final json file in the report directory called index.json.
At the afterRunHook stage the file is mochawesome.json.
Before aggregation
After aggregation

Neovim built-in LSP shows No code actions available for Python files

When I open a python file, diagnostics seem to be working fine. Then I navigate to a line with a diagnostic error, press the shortcut to invoke code actions ('<space>ca' in my case) and I get a message 'No code actions available'. I have tried running it for different errors, like the following ones:
b =1 #E225 missing whitespace around operator
from jinja2 import StrictUndefined #'jinja2.StricUndefined' imported but unused
import jjj # import-error: Unable to import 'jjj'
I have tried two LSP servers so far: pyright and pylsp, both gave me the same 'No code actions available'
I've seen a similar question but JavaScript asked here and it suggest installing a plugin but that didn't work for me.
Both Pyright and Pyls don't provide any diagnostic solving code actions like jdtls for java unfortunately...
I would recommend checking out their individual repositories on github for further information and development:
pyls,
pyright
For more insight on what your language server is capable of, run the following command in vim:
:lua print(vim.inspect(vim.lsp.buf_get_clients()[1].resolved_capabilities))
It will output the capabilities of the language server you are attached to in the current buffer.
For example this is the output for Pyright with no special configurations:
{
call_hierarchy = true,
code_action = {
codeActionKinds = { "quickfix", "source.organizeImports" },
workDoneProgress = true
},
code_lens = false,
code_lens_resolve = false,
completion = true,
declaration = false,
document_formatting = false,
document_highlight = {
workDoneProgress = true
},
document_range_formatting = false,
document_symbol = {
workDoneProgress = true
},
execute_command = true,
find_references = {
workDoneProgress = true
},
goto_definition = {
workDoneProgress = true
},
hover = {
workDoneProgress = true
},
implementation = false,
rename = true,
signature_help = true,
signature_help_trigger_characters = { "(", ",", ")" },
text_document_did_change = 2,
text_document_open_close = true,
text_document_save = true,
text_document_save_include_text = false,
text_document_will_save = false,
text_document_will_save_wait_until = false,
type_definition = false,
workspace_folder_properties = {
changeNotifications = false,
supported = false
},
workspace_symbol = {
workDoneProgress = true
}
}
Currently Pyright only supports the organize imports code action.
Keep in mind some lsp's don't provide code actions at all, but generally they do provide the basic needs such as go-to definition/declaration, hover info, documentation, signature help, renaming and references.

Vscode language server extension connection.onCompletion

I am creating a language server. Specifically, the issue is with completions. I'm returning a big list of completion items but whenever I test my language the completion provider simply will not suggest anything after I type a dot(.) when I'm expecting it to suggest, essentially, class members associated with the symbol left of said dot(.). Don't get me wrong, suggestions work until I type the dot(.) character and then it says, "No Suggestions".
Also, I'm trying to implement this server side and not client side.
EDIT:
Essentially, I'm assembling a big list and returning it.
connection.onInitialize((params: node.InitializeParams) => {
workspaceFolder = params.workspaceFolders![0].uri;
const capabilities = params.capabilities;
// Does the client support the `workspace/configuration` request?
// If not, we fall back using global settings.
hasConfigurationCapability = !!(
capabilities.workspace && !!capabilities.workspace.configuration
);
hasWorkspaceFolderCapability = !!(
capabilities.workspace && !!capabilities.workspace.workspaceFolders
);
hasDiagnosticRelatedInformationCapability = !!(
capabilities.textDocument &&
capabilities.textDocument.publishDiagnostics &&
capabilities.textDocument.publishDiagnostics.relatedInformation
);
capabilities.workspace!.workspaceEdit!.documentChanges = true;
const result: node.InitializeResult = {
capabilities: {
textDocumentSync: node.TextDocumentSyncKind.Incremental,
colorProvider: true,
hoverProvider: true,
definitionProvider: true,
typeDefinitionProvider: true,
referencesProvider: true,
documentHighlightProvider: true,
documentSymbolProvider: true,
workspaceSymbolProvider: true,
// codeActionProvider: true,
codeLensProvider: {
resolveProvider: true,
workDoneProgress: false
},
// Tell the client that this server supports code completion.
completionProvider: {
resolveProvider: true,
workDoneProgress: false,
triggerCharacters: ['.', '/'],
allCommitCharacters: ['.']
},
signatureHelpProvider: {
triggerCharacters: ['('],
retriggerCharacters: [','],
workDoneProgress: false
},
executeCommandProvider: {
commands: ["compile"],
workDoneProgress: false
},
semanticTokensProvider: {
documentSelector: [{ scheme: 'file', language: 'agc' }],
legend: {
tokenTypes: gTokenTypes,
tokenModifiers: gTokenModifiers
},
full: true,
workDoneProgress: false
}
}
};
if (hasWorkspaceFolderCapability) {
result.capabilities.workspace = {
workspaceFolders: {
supported: true
}
};
}
return result;
});
// This handler provides the initial list of the completion items.
connection.onCompletion(
async (params: node.TextDocumentPositionParams): Promise<node.CompletionItem[] | node.CompletionList | undefined> => {
console.log("completion");
let doc = documents.get(params.textDocument.uri);
let list:node.CompletionList = node.CompletionList.create([], true);
list.items = list.items.concat(comp.GetAGKKeywordCompletionItems(), comp.GetAGKCommandCompletionItems(), agkDocs.getALLCompletionItems());
list.items.push(sense.GetCommentSnippetCompletionItem(doc, params.position));
list.items.push(sense.GetCommentSnippetCompletionItem(doc, params.position, true));
console.log("END completion");
return list;
}
);

Why is my Workbox GenerateSW showing my offline page while connected?

I'm trying to setup my offline page using Workbox GenerateSW() and running into an issue where on the first load after I clear site data and hard refresh displays my homepage, but on subsequent loads I am getting the offline page I set up even though I'm online. I have a multi page PHP app that has the assets served up by a CDN. I run the GenerateSW() task in a JS file called by an npm node script.
Here is my GenerateSW() code...
// Pull in .env file values...
const dotEnv = require('dotenv').config({ path: '/var/www/my-project/sites/www/.env' });
if (dotEnv.error) {
throw dotEnv.error
}
const {generateSW} = require('workbox-build');
// Used to break cache on generate of new SW where file is composed of multiple pieces that can't be watched.
const genRanHex = (size = 24) => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');
const mode = 'development';
generateSW({
swDest: './sites/www/public/service-worker.js',
skipWaiting: true,
clientsClaim: true,
cleanupOutdatedCaches: true,
cacheId: genRanHex(),
mode: mode,
navigateFallback: '/offline',
offlineGoogleAnalytics: mode === 'production',
globDirectory: './sites/assets/public',
globPatterns: [
'img/shell/**/*.{svg,png}',
'dist/**/*.{js,css}',
'manifest.json'
],
modifyURLPrefix: {
'dist/': `${dotEnv.parsed.APPLICATION_ASSETS_CDN}/dist/`,
'img/shell/': `${dotEnv.parsed.APPLICATION_ASSETS_CDN}/img/shell/`,
},
ignoreURLParametersMatching: [/v/],
additionalManifestEntries: [
{
"url": "/offline",
"revision": genRanHex()
}
],
runtimeCaching: []
}).then(({count, size}) => {
console.log(`Generated service worker, which will precache ${count} files, totaling ${size} bytes.`);
}).catch(console.error);
navigateFallback is not actually offline page. From workbox docs:
If specified, all navigation requests for URLs that aren't precached will be fulfilled with the HTML at the URL provided. You must pass in the URL of an HTML document that is listed in your precache manifest. This is meant to be used in a Single Page App scenario, in which you want all navigations to use common App Shell HTML.
For offline page, this question might help.
So the accepted answer was correct in my misuse of navigateFallback which I was trying to use as an offline fallback for non cached routes. After some digging and tinkering, I found the correct way to go about it. The important part that I missed or was not documented well enough on Workbox is that the offline fallback happens at the runtimeCache level...
// Pull in .env file values...
const dotEnv = require('dotenv').config({ path: '/var/www/my-project/sites/www/.env' });
if (dotEnv.error) {
throw dotEnv.error
}
const {generateSW} = require('workbox-build');
// Used to break cache on generate of new SW where file is composed of multiple pieces that can't be watched.
const genRanHex = (size = 24) => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');
const mode = 'development';
generateSW({
swDest: './sites/www/public/service-worker.js',
skipWaiting: true,
clientsClaim: true,
cleanupOutdatedCaches: true,
cacheId: genRanHex(),
mode: mode,
offlineGoogleAnalytics: mode === 'production',
globDirectory: './sites/assets/public',
globPatterns: [
'img/shell/**/*.{svg,png}',
'dist/**/*.{js,css}',
'manifest.json'
],
modifyURLPrefix: {
'dist/': `${dotEnv.parsed.APPLICATION_ASSETS_CDN}/dist/`,
'img/shell/': `${dotEnv.parsed.APPLICATION_ASSETS_CDN}/img/shell/`,
},
ignoreURLParametersMatching: [/v/],
additionalManifestEntries: [
{
"url": "/offline",
"revision": genRanHex()
}
],
runtimeCaching: [
{
urlPattern: /^https:\/\/([\w+\.\-]+www\.mysite\.tv)(|\/.*)$/,
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'core',
precacheFallback: {
fallbackURL: '/offline' // THIS IS THE KEY
}
}
}
]
}).then(({count, size}) => {
console.log(`Generated service worker, which will precache ${count} files, totaling ${size} bytes.`);
}).catch(console.error);

Using react-hot-loader with custom babel preset

My app doesn't support older browsers, and I like to trim down the set of Babel transforms to make the code easier to debug (so that the code in the debugger looks like more the original source).
However, when I migrate to react-hot-loader 3, this no longer works. That is, I can get RHL 3 to work with the standard es2015 preset, but not with my custom set of transforms. What happens is that the react components are rendered but never mounted, and won't respond to any events.
The set of transforms I am trying to use is:
var babel_plugins = [
'transform-runtime',
'transform-object-rest-spread',
// Transforms needed for modern browsers only
'babel-plugin-check-es2015-constants',
'babel-plugin-transform-es2015-block-scoping',
'babel-plugin-transform-es2015-function-name',
'babel-plugin-transform-es2015-parameters',
'babel-plugin-transform-es2015-destructuring',
// No longer needed with Webpack 2
// 'babel-plugin-transform-es2015-modules-commonjs',
'react-hot-loader/babel',
];
In response to the comments, here's more information:
Here's how I'm using the AppContainer:
export default (
<AppContainer>
<Router history={browserHistory}>
(My routes here...)
</Router>
</AppContainer>
);
And here's my dev server setup:
// Adjust the config for hot reloading.
config.entry = {
main: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://127.0.0.1:8000', // WebpackDevServer host and port
'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors
'./src/main.js', // Your appʼs entry point
],
frame: './src/frame_main.js', // Entry point for popup tab
};
config.plugins.push(new webpack.HotModuleReplacementPlugin());
const compiler = webpack(config);
const server = new WebpackDevServer(compiler, {
contentBase: path.resolve(__dirname, '../builds/'),
historyApiFallback: true,
stats: 'errors-only',
hot: true,
});
server.listen(8000, '127.0.0.1', () => {});
Here's the relevant portion of my webpack config:
test: /\.jsx?$/,
include: __dirname + '/src',
exclude: __dirname + '/src/libs',
use: [
{
loader: 'babel-loader',
options: {
plugins: babel_plugins,
presets: babel_presets
},
},
{
loader: 'eslint-loader',
},
]