小编Luk*_*kas的帖子

如果参数是数组,则返回值数组,否则返回值

我想允许一个string或一个 s 数组string作为参数。根据是否传递了一个string或一个数组,我想返回一个值或一个值数组。string

function(input: string | string[]): inputIsArray ? returnValue[] : returnValue {}
Run Code Online (Sandbox Code Playgroud)

我怎样才能为此编写正确的类型?

typescript typescript-typings

7
推荐指数
1
解决办法
1637
查看次数

有没有办法在VirtualBox中运行Android TV?

我想试用Android TV,并可能为它开发一个应用程序.我想先看看操作系统.有没有办法在虚拟机中运行Android TV,例如使用VirtualBox?

virtualbox android-tv

6
推荐指数
1
解决办法
9837
查看次数

加载Web组件时的事件

我有一个像这样的Web组件

<template id="component">
    <link href="/static/css/main.cacbacc7.css" rel="stylesheet">
    <script src="/static/js/vendor.js" type="text/javascript"></script>
    <script src="/static/js/bundle.js" type="text/javascript"></script>
    <span id="react-app"></span>
</template>

<script>
  (function (window, document) {
    const doc = (document._currentScript || document.currentScript).ownerDocument;
    const proto = Object.create(HTMLElement.prototype, {
      attachedCallback: {
        value: function () {
          const template = doc.querySelector('template#component').content;
          const shadowRoot = this.attachShadow({ mode: 'open' });
          shadowRoot.appendChild(template.cloneNode(true));
          // executeThis() when all scripts have been loaded
        }
      },
    });
    document.registerElement('react-webcomponent', { prototype: proto });
  })(window, document);
</script>
Run Code Online (Sandbox Code Playgroud)

我可以知道我的所有script标签何时template被加载?

更新

我目前正在做的是

const scripts = [...shadowRoot.querySelectorAll('script')];
let …
Run Code Online (Sandbox Code Playgroud)

javascript web-component

6
推荐指数
1
解决办法
2056
查看次数

编译后修改文件的webpack插件

我正在编写一个 Webpack 插件,该插件应该用 Webpack 生成的 CSS 文件列表替换部分 JS 代码。对这个 JS 代码进行成像:

ReactWebComponent.create(<App />, 'react-web-component', { injectReactWebComponent: true });
Run Code Online (Sandbox Code Playgroud)

我想更换injectReactWebComponent: true零件

injectReactWebComponent: '<link href="static/css/main.cacbacc7.css" rel="stylesheet">'
Run Code Online (Sandbox Code Playgroud)

而那个链接标签是一个由 Webpack 生成的文件。

我的(某种工作)代码如下:

ReactWebComponent.prototype.apply = function(compiler) {
  compiler.plugin('emit', function(compilation, callback) {
    const cssFiles = Object.keys(compilation.assets)
        .filter(fileName => /\.css$/.test(fileName));

    const jsFiles = Object.keys(compilation.assets)
        .filter(fileName => /\.js$/.test(fileName));

    const cssLinkTagsAsString = cssFiles
        .map(fileName => `<link href="${fileName}" rel="stylesheet">`)
        .join('');

    jsFiles.forEach(fileName => {
      compilation.assets[fileName].children.forEach(child => {
        if (child._value) {
          child._value = child._value.replace(/injectReactWebComponent\s*:\s*true/g, `injectReactWebComponent: \'${cssLinkTagsAsString}\'`);
        }
      });
    });

    callback(); …
Run Code Online (Sandbox Code Playgroud)

webpack webpack-plugin extract-text-plugin

6
推荐指数
1
解决办法
6103
查看次数

如何使用jest测试unhandledRejection/uncaughtException处理程序

我有unhandledRejections和uncaughtExceptions的处理程序:

bin.js

['unhandledRejection', 'uncaughtException'].forEach(event => {
  process.on(event, err => logger.error(err));
});
Run Code Online (Sandbox Code Playgroud)

现在我想测试它们jest:

bin.test.js

const bin = require('../bin');

test('catches unhandled rejections', async () => {
  const error = new Error('mock error');
  await Promise.reject(error);
  expect(logger.error).toHaveBeenCalledWith(error);
});

test('catches uncaught exceptions', () => {
  const error = new Error('mock error');
  throw error;
  expect(logger.error).toHaveBeenCalledWith(error);
});
Run Code Online (Sandbox Code Playgroud)

jest只是告诉我测试中有错误:

●捕获未处理的拒绝

mock error

   8 | // https://github.com/facebook/jest/issues/5620
   9 | test('catches unhandled rejections', async () => {
> 10 |   const error …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing jestjs

6
推荐指数
2
解决办法
444
查看次数

使用 typescript 输入 jest test.each 标记的模板文字

我正在尝试输入一个test.each使用标记模板文字的笑话

test.each`
  height | text
  ${10}  | ${undefined}
  ${20}  | ${undefined}
  ${10}  | ${'text'}
  ${20}  | ${'text'}
`('$height and $text work as expected', ({ height, text }) => {
  //...
});
Run Code Online (Sandbox Code Playgroud)
  • height是一个数字
  • text是一个字符串或未定义

当然,我可以将我的类型添加到测试的函数参数中:

({ height, text }: { height: number, text: string? }) => {
  //...
});
Run Code Online (Sandbox Code Playgroud)

但这不是我想要的。test.each接受泛型类型

({ height, text }: { height: number, text: string? }) => {
  //...
});
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用该类型来推断函数参数中的类型。

typescript jestjs

6
推荐指数
1
解决办法
6007
查看次数

无法从.ts文件导入.tsx文件(反之亦然)

我有一个项目.ts.tsx文件,我试图.tsx.ts文件导入文件,如下所示:

SRC/index.ts

import WriteEditor from './write_editor';
Run Code Online (Sandbox Code Playgroud)

SRC/write_editor.tsx

import Events from './events';
import Actions from './actions';

export default class WriteEditor extends React.Component { /*...*/ }
Run Code Online (Sandbox Code Playgroud)

现在TypeScript告诉我

./src/index.ts中的错误找不到模块:错误:无法解析'/ Users/luke/Projekte/writejs/code/writejs/src'中的'./write_editor'@ ./src/index.ts 3 :23-48 @ multi ./src/index.ts

所以我尝试了这个:

SRC/index.ts

import WriteEditor from './write_editor.tsx';
Run Code Online (Sandbox Code Playgroud)

现在我的IDE告诉我不要编写扩展tsx,我在src/write_editor.tsx中收到错误,因为TypeScript无法.ts.tsx文件中找到我的文件.

然后我去重命名导入并添加.ts扩展名

import Events from './events.ts';
import Actions from './actions.ts';
Run Code Online (Sandbox Code Playgroud)

现在我收到吨或错误告诉我根本不写扩展.

那么我们如何从中导入tsx,ts反之亦然?

typescript webpack babeljs

5
推荐指数
2
解决办法
4184
查看次数

Webpack Dev Server 包含用于观看的附加文件

我正在开发服务器端渲染器,Vue并将其用作webpack dev server开发服务器。它已经工作得很好,我已经设置了服务器,以便在源文件之一发生更改时触发构建。当然,它是开箱即用的,因为我的源文件是配置entry中的一部分webpack

现在,Vue您还可以指向html用作服务器端渲染模板的文件。将 html 文件传递​​给 Vue 进行服务器端渲染非常简单。

现在我想做的是Vue每次html文件更改时更新服务器端渲染器。所以基本上我需要做的就是告诉webpackwebpack dev server分别监视该html文件上的文件更改。

我怎样才能做到这一点?

对于上下文,这是我的配置的要点webpack

module.exports = {
  entry: {
    client: 'src/path/to/client.js',
  },
  output: {
    path: appDist,
    publicPath: '/',
    filename: '[name].[chunkhash].js',
  },
  resolve: {
    extensions: ['.vue', '.js', '.json', '.mjs'],
  },
  module: {
    rules: [/* ...*/],
  },
  /* some other options here */
  devServer: {
    contentBase: [appDist, appPublic],
    publicPath: …
Run Code Online (Sandbox Code Playgroud)

javascript webpack vue.js

5
推荐指数
0
解决办法
1813
查看次数

使用汇总创建树可摇晃的库

我正在尝试创建一个组件库,例如Wie Rollup和Vue,当其他人将其导入时,它们可以被树摇晃。我的设置如下:

相关摘录 package.json

{
  "name": "red-components-with-rollup",
  "version": "1.0.0",
  "sideEffects": false,
  "main": "dist/lib.cjs.js",
  "module": "dist/lib.esm.js",
  "browser": "dist/lib.umd.js",
  "scripts": {
    "build": "rollup -c",
    "dev": "rollup -c -w"
  },
  "devDependencies": {
    /* ... */
}
Run Code Online (Sandbox Code Playgroud)

这是我的全部 rollup.config.js

import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import vue from "rollup-plugin-vue";
import pkg from "./package.json";

export default {
  input: "lib/index.js",
  output: [
    {
      file: pkg.browser,
      format: "umd",
      name: "red-components"
    },
    { file: pkg.main, format: "cjs" },
    { file: pkg.module, format: "es" }
  ],
  plugins: …
Run Code Online (Sandbox Code Playgroud)

javascript rollup bundling-and-minification vue.js tree-shaking

5
推荐指数
1
解决办法
265
查看次数

根据 TypeScript 中的参数动态生成返回类型

我有一个函数,它接收字符串数组并返回一个对象,其键是字符串,每个值是undefined

function getInitialCharacteristics(names: string[]): ??? {
  return names.reduce((obj, name) => ({ ...obj, [name]: undefined }), {});
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

const result = getInitialCharacteristics(["hello", "world"]);
// result == { hello: undefined, world: undefined }
Run Code Online (Sandbox Code Playgroud)

现在我想知道如何定义使用 TypeScript 的正确返回值getInitialCharacteristics。我必须使用泛型或以某种方式动态生成该类型。那可能吗?

typescript typescript-typings

5
推荐指数
1
解决办法
2125
查看次数