Giter VIP home page Giter VIP logo

lisonge / vite-plugin-monkey Goto Github PK

View Code? Open in Web Editor NEW
1.3K 1.3K 68.0 2.15 MB

A vite plugin server and build your.user.js for userscript engine like Tampermonkey, Violentmonkey, Greasemonkey, ScriptCat

License: MIT License

Shell 0.06% TypeScript 83.96% CSS 9.14% JavaScript 4.09% Svelte 1.07% Vue 1.58% PowerShell 0.10% SCSS 0.02%
greasemonkey rollupjs scriptcat tampermonkey userscript violentmonkey vite vite-plugin

vite-plugin-monkey's Introduction

gu gu gu

visit count

vite-plugin-monkey's People

Contributors

andywang425 avatar coaixy avatar hxrealm avatar lcandy2 avatar linlin00000000 avatar lisonge avatar magicdawn avatar malix-off avatar mutoe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

vite-plugin-monkey's Issues

watch 模式下,external依赖产生的require会错误的增生

使用以下 config 搭配 vite build --watch

monkey({
  build: {
      externalGlobals: {
          'sentinel-js': cdn.cdnjs('sentinel', 'sentinel.min.js'),
      }
  }
})

触发多次rebuild后会得到

// ==UserScript==
// @name         知乎助手
// @namespace    pionxzh
// @version      1.0.0
// @author       pionxzh
// @description  自动屏蔽来自黑名单的所有评论与文章
// @license      MIT
// @icon         https://static.zhihu.com/heifetz/favicon.ico
// @match        *.zhihu.com/*
// @require      https://cdnjs.cloudflare.com/ajax/libs/sentinel-js/0.0.5/sentinel.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/sentinel-js/0.0.5/sentinel.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/sentinel-js/0.0.5/sentinel.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/sentinel-js/0.0.5/sentinel.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/sentinel-js/0.0.5/sentinel.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/sentinel-js/0.0.5/sentinel.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/sentinel-js/0.0.5/sentinel.min.js
// @grant        GM_getValue
// @grant        GM_setValue
// ==/UserScript==

配置也可以参考 /pionxzh/userscripts/packages/zhihu/vite.config.ts

[功能请求] 增加一个输出 .meta.js 的构建选项

.meta.js 只会包含 UserScript 注释,不包含代码正文,Tampermonkey 等脚本插件会自动使用该文件检查脚本更新而不必下载完整脚本,Greasy Fork 等脚本托管网站也会自动提供该文件(可以随便找个脚本链接把 .user.js 替换为 .meta.js 访问看看)

如果是使用 Github Pages 等托管脚本的话,自动生成 .meta.js 会很有用

BUG : `@antifeature`

Exemple

...
userscript: {
    ...
    antifeature: {
	    type: "tracking",
	    description: "test"
    },
    ...
},
...

build:

// @antifeature  trackingtest

Cause

#41

拒绝执行内联脚本

vite.config.js

import { defineConfig } from 'vite';
import monkey from 'vite-plugin-monkey';
import eslintPlugin from 'vite-plugin-eslint';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    monkey({
      entry: 'src/main.js',
      userscript: {
        icon: 'https://vitejs.dev/logo.svg',
        namespace: 'npm/vite-plugin-monkey',
        match: ['*://github.com/*'],
        'run-at': 'document-end',
      },
    }),
    eslintPlugin(),
  ],
});

main.js

console.log('lala');

image

报错文字如下:

userscript.html?name=server%253Agithub.user.js&id=8a1c944e-1d66-47f8-8d2c-fb2eef8448a2:79 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'unsafe-eval' github.githubassets.com". Either the 'unsafe-inline' keyword, a hash ('sha256-m9WuhxCDjalzF2tBhg/f0YTfasIeLnFGhEK6+zp1IZw='), or a nonce ('nonce-...') is required to enable inline execution.

如果说 github 做了限制,那么其他脚本应该也无法正常运行。但我只是简单的加了一个 console.log 就无法运行,感觉是不是哪里出问题了。

引入css文件压缩问题

如图:
image
image

引入css后,生成的脚本文件的css样式为一串字符串,压缩一下是否更好呢。
image

conflict to vue with vue-router when building

~/project/luogu/luogu-ex-backstage $ vite build
vite v2.9.13 building for production...
✓ 26 modules transformed.
Invalid value "iife" for option "output.format" - UMD and IIFE output formats are not supported for code-splitting builds.
error during build:
Error: Invalid value "iife" for option "output.format" - UMD and IIFE output formats are not supported for code-splitting builds.
    at error (/usr/local/lib/node_modules/vite/node_modules/rollup/dist/shared/rollup.js:198:30)
    at validateOptionsForMultiChunkOutput (/usr/local/lib/node_modules/vite/node_modules/rollup/dist/shared/rollup.js:16265:16)
    at Bundle.generate (/usr/local/lib/node_modules/vite/node_modules/rollup/dist/shared/rollup.js:16099:17)
    at async /usr/local/lib/node_modules/vite/node_modules/rollup/dist/shared/rollup.js:23732:27
    at async catchUnfinishedHookActions (/usr/local/lib/node_modules/vite/node_modules/rollup/dist/shared/rollup.js:23174:20)
    at async doBuild (/usr/local/lib/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:41696:26)
    at async build (/usr/local/lib/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:41527:16)
    at async CAC.<anonymous> (/usr/local/lib/node_modules/vite/dist/node/cli.js:738:9)

externalResource 中 raw / url 导入的处理问题

if (suffixSet.has('url') || suffixSet.has('inline')) {
moduleCode = [
`import {urlLoader as loader} from 'virtual:plugin-monkey-loader'`,
`export default loader(...${JSON.stringify([
resourceName,
mimeType,
])})`,
].join(';');
} else if (suffixSet.has('raw')) {
moduleCode = [
`import {rawLoader as loader} from 'virtual:plugin-monkey-loader'`,
`export default loader(...${JSON.stringify([resourceName])})`,
].join(';');
}
if (ext == 'json') {
// export name will bring side effect
moduleCode = [
`import {jsonLoader as loader} from 'virtual:plugin-monkey-loader'`,
`export default loader(...${JSON.stringify([resourceName])})`,
].join(';');
} else if (ext == 'css') {
moduleCode = [
`import {cssLoader as loader} from 'virtual:plugin-monkey-loader'`,
`export default loader(...${JSON.stringify([resourceName])})`,
].join(';');
} else if (KNOWN_ASSET_TYPES.has(ext)) {
const mediaType = mimes[ext];
moduleCode = [
`import {urlLoader as loader} from 'virtual:plugin-monkey-loader'`,
`export default loader(...${JSON.stringify([
resourceName,
mediaType,
])})`,
].join(';');
}

此处的 else if 在扩展名判断处断开了,导致扩展名处理会覆盖 raw / url 的处理,按理来说应该全部用 else if 连接

自动导入依赖的依赖

pinia 依赖 vue-demi
但是当我写在 externalGlobals 里时不会自动导入
估计是没有安装和没引用 但是 pinia 里确实使用到了该包

支持多国语系配置 name, description

根据 https://greasyfork.org/zh-CN/help/meta-keys#meta-name-localized

希望可以提供某种方式来配置这种语言相关的meta

@name:XX-YY
脚本在特定语言区域的标题。XX 指 ISO 639-1 国家代码 以及 YY 指可选的 ISO 3166 地区代码。该选项用于提供多语言的@name 脚本名称。
@description:XX-YY
用某门语言写成的脚本描述。XX 指 ISO 639-1 国家代码 以及 YY 指可选的 ISO 3166 地区代码。该选项用于提供多语言的@description 脚本介绍。

Error initializing project 初始化项目出错

After initializing the project, the following error is reported when executing npm run dev

在初始化项目之后,执行 npm run dev的时候报如下错误

`
shell
npm create monkey

cd xxx

npm install

npm run dev
`

[email protected] dev
vite

failed to load config from /Users/xxx/Code/xxx_plugin/vite.config.ts
error when starting dev server:
SyntaxError: Unexpected token '||='
at Loader.moduleStrategy (internal/modules/esm/translators.js:145:18)

how to disable Content Security Policy (CSP) include http-csp and html-csp

Now just use browser extension Disable-CSP

  • disable http header csp
  • disable html meta csp

updated to 2023-07-20 20:48


    Refused to load the script 'http://127.0.0.1:3000/@vite/client' because it violates the following Content Security Policy directive: "script-src 'unsafe-eval' 'self' data: 'unsafe-inline' https://checkout.stripe.com/checkout.js https://checkout.stripe.com https://js.stripe.com/v3 https://platform.twitter.com/widgets.js https://static.npmjs.com/". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

(匿名) @ userscript.html?name=dev%253Avite-userscript-template.user.js&id=289d436b-2813-44f5-b751-16c871c6e093:105
10:25:04.643 userscript.html?name=dev%253Avite-userscript-template.user.js&id=289d436b-2813-44f5-b751-16c871c6e093:105 
        
       Refused to load the script 'http://127.0.0.1:3000/src/main.ts' because it violates the following Content Security Policy directive: "script-src 'unsafe-eval' 'self' data: 'unsafe-inline' https://checkout.stripe.com/checkout.js https://checkout.stripe.com https://js.stripe.com/v3 https://platform.twitter.com/widgets.js https://static.npmjs.com/". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

[功能请求] 新增一种可以让 resource 使用的 cdn 工具函数

我感觉在 resource 里添加 cdn 上的 css 这种使用方式挺常见的,能否让 resource 跟 externalGlobals 一样支持使用 cdn 工具函数

(想了下好像不太对,应该是需要一种新的 cdn 工具函数能直接返回 cdn 地址字符串,主要是为了可以动态获取版本号)

[plugin-monkey] not found module vue version, use vue@latest

package.json

{
  "name": "vite-vue-typescript-starter",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vue-tsc --noEmit && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "vue": "^3.2.37"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^2.3.3",
    "typescript": "^4.6.4",
    "vite": "^2.9.13",
    "vue-tsc": "^0.38.2",
    "vite-plugin-monkey": "0.2.13"
  }
}

when set "type": "module", plugin can not found module

怎么获取 MonkeyOption 这个 type

看代码没有 export,不能直接 import 这个类型

这样倒是可以,但感觉不太好

import type { MonkeyOption } from 'vite-plugin-monkey/src/node/types';

Userscript has incorrect name if `author` in package.json is specified as object

The author field in package.json can be specified as a string or the object

{
  name: string,
  email?: string,
  url?: string,
}

In the latter case, the author.name is used as the userscript name instead of the name field from package.json which is of course incorrect.

Example

If package.json has the following fields:

"name": "script_name",
"author": {
  "name": "author_name"
},

the userscript will be compiler with the name author_name instead of script_name.

导入vue时的相对参考路径问题

前提:只修改了vite.config.js中的match。
控制台:
Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".

部分依赖在油猴的环境中直接简单地用 @require 引入会产生冲突

例如

// @require      https://unpkg.com/[email protected]//dist/vue.global.prod.js
// @require      https://unpkg.com/[email protected]//dist/index.full.js          // element-plus 依赖 vue

vue.js 会导出一个变量 Vue,element 会寻找 this.Vue 当成依赖,但是在油猴的环境中 this 被重定向到了 window 的一个 proxy(@grant none 就会指向空对象),所以就会发生报错说 vue is not found,即使 vue 变量已经在环境中了。

所以能不能提供一个自定义依赖引入的方法呢?

打包问题

使用除vue外引入其他cdn的情况,开发环境正常,打包后无法正常运行。
image

开启了minifyCss时,打包得到的css没有遵循vite构建选项里的build.cssTarget

环境

Windows 10
Chrome v83
vite-plugin-monkey v2.10.0

简述

设置了vite构建选项build.cssTargetnpm run build后发现,HelloWorld.vue.read-the-docs的定位样式被编译为了inset:60px 0 0 260px;,而inset是chrome87才开始支持的,所以似乎是某种处理导致build.cssTarget没有生效。

vite.config.ts

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import monkey, { cdn } from 'vite-plugin-monkey';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    monkey({
      entry: 'src/main.ts',
      userscript: {
        icon: 'https://vitejs.dev/logo.svg',
        namespace: 'npm/vite-plugin-monkey',
        match: ['https://www.google.com/'],
      },
      build: {
        minifyCss: true,
        externalGlobals: {
          vue: cdn.jsdelivr('Vue', 'dist/vue.global.prod.js'),
        },
      },
    }),
  ],
  build: {
    cssTarget: 'chrome83',
  }
});

src/components/HelloWorld.vue

<style scoped>
.read-the-docs {
  color: #888;
  position: fixed;
  top: 60px;
  right: 0;
  bottom: 0;
  left: 260px;
  background: #fff;
  z-index: 1050;
  padding: 10px 20px 200px 20px;
  overflow-y: auto;
  box-shadow: -2px 2px 6px #bbbbbb;
}
</style>

麻烦大神看一下是怎么回事,感谢!

打包后字符串中的中文被转义

如以下 js 代码:

ClickSelector('button', '确认')

在打包后会变成:

ClickSelector("button", "\u786E\u8BA4");

用倒是能用,但是在油猴插件中直接查看代码的时候就看不懂写的是什么了。

使用vue的js模板构建的项目,无法使用pnpm run dev 预览脚本。I can't preview the script.

我的环境 My context

  • edge
  • js+vue
  • image

发生的问题 Problems that occur

使用命令「pnpm run dev」预览脚本,添加脚本后打开匹配网站,在控制台出现如下错误
Use the command "pnpm run dev" to preview the project, an error occurred at the console, the project preview failed.
image
client.ts:470:16 in
image
style.css:1:96 in
image

如何复现 Reproduction of the problem

修改vite.config.js 中的
Modify the file "vite.config.js "
image

更多 More

当我直接构建项目然后导入至油猴插件时,脚本就能正常运行了。
我尝试过直接使用模板在该网站预览,还是会发生同样的错误。
使用该项目在其他网站预览(例如哔哩哔哩),就不会发生这种问题。

When I build the project directly and import it into the Monkey, the script works fine.
I preview the template project on the website and the same error still occurs.
If i preview the project on other websites ( For example, bilibili ), the error does not occur.

以上就是我的问题了,感谢大佬抽空查看我的问题,如果有解决方案就更好了。(一个前端小白)也许我可能遗留了某些配置文件吧,求大佬轻喷。

can not work with vite plugin @vitejs/plugin-react

@vitejs/plugin-react will inject

  <script type="module">
import RefreshRuntime from "/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>

to index.html document.head

but vite-plugin-monkey existing installation mode will just inject /@vite/client and /src/main.jsx

so React and @vitejs/plugin-react can not work with vite-plugin-monkey

finallly, vite-plugin-monkey need to use other installation

Invalid package version deduction

I am adding a package that is in the beta:

npm install @formkit/vue
npm show @formkit/vue

# @formkit/[email protected]

Then I set up the CDN:

'@formkit/vue': cdn.jsdelivr('FormKit', 'dist/formkit-vue.js'),

During the build, the following message appears:

[plugin-monkey] not found module @formkit/vue version, use @formkit/vue@latest

The resulting file has an invalid URL to the package:

// @require      https://cdn.jsdelivr.net/npm/@formkit@latest/dist/formkit-vue.js

I am using the following workaround:

'@formkit/vue': [
    'FormKit',
    (version: string) => `https://cdn.jsdelivr.net/npm/@formkit/vue@${version}/dist/formkit-vue.js`,
],
// @require      https://cdn.jsdelivr.net/npm/@formkit/vue@latest/dist/formkit-vue.js

Cannot build while there is another SSR plugin in the same config

Issue

I am developing a SvelteKit website which in I do host my Tampermonkey's userscripts.
I can't manage to make the plugin be built after I added my svelte website to the repo.

adding

rollupOptions: {
	output: {
		inlineDynamicImports: false,
	},
},

in the build vite config option doesn't work as SvelteKit:

The following Vite config options will be overridden by SvelteKit:
  - build.rollupOptions.input

config.build.externalGlobals, submodule cannot get correct version

import { defineConfig } from 'vite';
import monkey, { cdn } from 'vite-plugin-monkey';
import cleanCss from './plugins/cleanCss';
import fs from 'node:fs/promises';
import type PrettierPkgR from 'prettier/package.json';

const prettierPkg: typeof PrettierPkgR = JSON.parse(
  (await fs.readFile('./node_modules/prettier/package.json')).toString('utf-8')
);

const pkgBaseUrl = 'https://unpkg.com/pkg-cdn/dist/';

const prettierCdn = (pkg: string) => {
  return [
    `prettierPlugins.${pkg}`,
    `https://cdn.jsdelivr.net/npm/prettier@${prettierPkg.version}/parser-${pkg}.js`,
  ] as [string, string];
};

export default defineConfig(({ command }) => {
  const multi = <T1, T2>(serve: T1, build: T2) => {
    return command == 'serve' ? serve : build;
  };
  return {
    plugins: [
      cleanCss(),
      monkey({
        entry: 'src/main.ts',
        userscript: {
          icon: 'https://vitejs.dev/logo.svg',
          name: 'v2ex评论markdown支持',
          description: 'v2ex评论markdown支持;代码语法高亮;代码自动格式化',
          namespace: 'https://github.com/lisonge',
          match: ['https://v2ex.com/t/*', 'https://www.v2ex.com/t/*'],
          version: multi('0.0.0', undefined),
        },
        build: {
          externalGlobals: {
            'markdown-it': cdn.jsdelivr(
              'markdownit',
              'dist/markdown-it.min.js'
            ),
            'highlight.js': [
              'hljs',
              (version) => {
                return `https://unpkg.com/@highlightjs/cdn-assets@${version}/highlight.min.js`;
              },
            ],
            prettier: cdn.jsdelivr('prettier', 'standalone.js'),
            'prettier/parser-babel': prettierCdn('babel'),
            'prettier/parser-yaml': prettierCdn('yaml'),
            'prettier/parser-postcss': prettierCdn('postcss'),
            'prettier/parser-html': prettierCdn('html'),
            'prettier-plugin-java': [
              'PrettierPluginJava',
              (version) =>
                `${pkgBaseUrl}prettier-plugin-java/v${version}.umd.js`,
            ],
          },
        },
      }),
    ],
  };
});

submodule prettier/* get version is always latest

externalResource 貌似不能正确支持 ?raw

我看到 externalResource 里面有处理 ?raw

} else if (importName.endsWith('?raw')) {
return miniCode(
[
`import {rawLoader as loader} from 'virtual:plugin-monkey-loader'`,
`export default loader(...${JSON.stringify([resourceName])})`,
].join(';'),
);
}

因此我猜想我应该是可以这样使用的

import { GM_addStyle } from '$';
import elementPlusCss from 'element-plus/dist/index.css?raw';
// 自行在某个需要的时候才动态引入
GM_addStyle(elementPlusCss);
// in monkey config
externalResource: {
  'element-plus/dist/index.css?raw': cdn.jsdelivrFastly(undefined, 'dist/index.css'),
}

但实际上不管用,经过测试我发现,问题出在这里

async resolveId(id) {
const { externalResource } = finalPluginOption.build;
if (id in externalResource) {
return '\0' + id + '\0';
}
},

不知道为什么此处 id 实际为 element-plus/dist/index.css?used&raw,多了个 used&,导致没有匹配上 externalResource

将 externalResource 配置里的 key 改为 element-plus/dist/index.css?used&raw 就可以顺利走进 load 钩子了,不过因为结尾并不是 ?raw 因此没有匹配上 raw 的处理,还是会有问题

参考lisonge/userscript项目遇到ReferenceError: __MONKEY_WINDOW__ is not defined

简述

shared/userscript-config/src/index.ts中引入了vite-plugin-monkey/dist/client中的方方法GM_getValue,用于某个自定义方法,在packages/gitrec中使用该自定义方法。而在构建packages/gitrec时,提示如下信息:

ReferenceError: __MONKEY_WINDOW__ is not defined
    at file:///home/runner/work/userscripts-lisonge/userscripts-lisonge/shared/userscript-config/dist/index.js:2:20
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:526:24)
    at async loadConfigFromBundledFile (file:///home/runner/work/userscripts-lisonge/userscripts-lisonge/node_modules/.pnpm/[email protected]_lx63oaw2dyx6c23wnkvjnvox4q/node_modules/vite/dist/node/chunks/dep-ca21228b.js:62337:21)
    at async loadConfigFromFile (file:///home/runner/work/userscripts-lisonge/userscripts-lisonge/node_modules/.pnpm/[email protected]_lx63oaw2dyx6c23wnkvjnvox4q/node_modules/vite/dist/node/chunks/dep-ca21228b.js:62222:28)
    at async resolveConfig (file:///home/runner/work/userscripts-lisonge/userscripts-lisonge/node_modules/.pnpm/[email protected]_lx63oaw2dyx6c23wnkvjnvox4q/node_modules/vite/dist/node/chunks/dep-ca21228b.js:6[18](https://github.com/northsea4/userscripts-lisonge/actions/runs/4288608080/jobs/7470804904#step:7:19)43:28)
    at async build (file:///home/runner/work/userscripts-lisonge/userscripts-lisonge/node_modules/.pnpm/[email protected]_lx63oaw2dyx6c23wnkvjnvox4q/node_modules/vite/dist/node/chunks/dep-ca21228b.js:44512:[20](https://github.com/northsea4/userscripts-lisonge/actions/runs/4288608080/jobs/7470804904#step:7:21))
    at async CAC.<anonymous> (file:///home/runner/work/userscripts-lisonge/userscripts-lisonge/node_modules/.pnpm/[email protected]_lx63oaw2dyx6c23wnkvjnvox4q/node_modules/vite/dist/node/cli.js:813:9)
undefined
/home/runner/work/userscripts-lisonge/userscripts-lisonge/packages/gitrec:
 ERR_PNPM_RECURSIVE_RUN_FIRST_FAIL  [email protected] build: `vite build`

复现

请查看 复现项目,最新的workflow pnpm version 7
也可以fork该测试仓库后手动运行 Test 这个workflow。
具体的测试代码请在commit test 中查看。

main.ts 中使用 await 关键字,build失败

感谢抽空查看我问题,我是前端新手,所以对问题的描述可能有点混乱,请见谅。

问题描述

注意:问题出现在使用build命令时,dev指令不会出现该错误

项目是以纯ts模式开发的,运行vite build出现以下错误:

PS G:\Code\tampermokey\steam-price-exchanger> vite build
vite v3.1.4 building for production...
✓ 14 modules transformed.
Module format iife does not support top-level await. Use the "es" or "system" output formats rather.
file: G:\Code\tampermokey\steam-price-exchanger\src\main.ts
error during build:
Error: Module format iife does not support top-level await. Use the "es" or "system" output formats rather.
    at error (file:///G:/Code/tampermokey/steam-price-exchanger/node_modules/rollup/dist/es/shared/rollup.js:1858:30)
    at Chunk.render (file:///G:/Code/tampermokey/steam-price-exchanger/node_modules/rollup/dist/es/shared/rollup.js:14844:20)
    at file:///G:/Code/tampermokey/steam-price-exchanger/node_modules/rollup/dist/es/shared/rollup.js:16006:52
    at Array.map (<anonymous>)
    at Bundle.addFinalizedChunksToBundle (file:///G:/Code/tampermokey/steam-price-exchanger/node_modules/rollup/dist/es/shared/rollup.js:16004:34)
    at Bundle.generate (file:///G:/Code/tampermokey/steam-price-exchanger/node_modules/rollup/dist/es/shared/rollup.js:15984:24)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async file:///G:/Code/tampermokey/steam-price-exchanger/node_modules/rollup/dist/es/shared/rollup.js:23754:27
    at async catchUnfinishedHookActions (file:///G:/Code/tampermokey/steam-price-exchanger/node_modules/rollup/dist/es/shared/rollup.js:23088:20)
    at async doBuild (file:///G:/Code/tampermokey/steam-price-exchanger/node_modules/vite/dist/node/chunks/dep-6b3a5aff.js:45818:26)

如何重现

可在此处查看项目代码

main.ts中使用await关键字,执行vite build指令失败,例如:

import {main} from './realMain'

await main()

main.ts中不使用await关键字,执行vite build指令成功,例如:

import {main} from './realMain'

main().then()

项目配置

可以在此处获取项目的源码

  • tsconfig.json
{
    "compilerOptions": {
        "experimentalDecorators": true,
        "target": "ESNext",
        "useDefineForClassFields": true,
        "module": "ESNext",
        "lib": [
            "ESNext",
            "DOM"
        ],
        "moduleResolution": "Node",
        "strict": true,
        "sourceMap": true,
        "resolveJsonModule": true,
        "isolatedModules": true,
        "esModuleInterop": true,
        "noEmit": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noImplicitReturns": true,
        "skipLibCheck": true
    },
    "include": [
        "src"
    ]
}
  • vite.config.ts
import {defineConfig} from 'vite'
import monkey from 'vite-plugin-monkey'

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        monkey({
            entry: 'src/main.ts',
            userscript: {
                name: 'steam价格转换',
                author: 'marioplus',
                description: 'steam商店中的价格转换为人民币',
                version: '1.0.0',
                icon: 'https://vitejs.dev/logo.svg',
                namespace: 'marioplus/steam-price-exchanger',
                match: [
                    'https://store.steampowered.com/*',
                    'https://steamcommunity.com/*'
                ],
                connect: [
                    'open.er-api.com',
                    'store.steampowered.com'
                ]
            },
        }),
    ],
})

尝试解决方案

将修改vite配置增加 build 配置

export default defineConfig({
    build: {
        lib: {
            entry: 'src/main.ts',
            formats: ['es'],
        },
        target: 'esnext'
    }
    ...
})

会出现以下错误

"C:\Program Files\nodejs\npm.cmd" run build

> [email protected] build
> tsc && vite build

vite v3.1.4 building for production...
✓ 15 modules transformed.
dist/steam-price-converter.user.js   90.44 KiB / gzip: 18.08 KiB
Module format iife does not support top-level await. Use the "es" or "system" output formats rather.
file: G:\Code\tampermokey\steam-price-converter\src\main.ts
error during build:
Error: Module format iife does not support top-level await. Use the "es" or "system" output formats rather.
    at error (file:///G:/Code/tampermokey/steam-price-converter/node_modules/rollup/dist/es/shared/rollup.js:1858:30)
    at Chunk.render (file:///G:/Code/tampermokey/steam-price-converter/node_modules/rollup/dist/es/shared/rollup.js:14844:20)
    at file:///G:/Code/tampermokey/steam-price-converter/node_modules/rollup/dist/es/shared/rollup.js:16006:52
    at Array.map (<anonymous>)
    at Bundle.addFinalizedChunksToBundle (file:///G:/Code/tampermokey/steam-price-converter/node_modules/rollup/dist/es/shared/rollup.js:16004:34)
    at Bundle.generate (file:///G:/Code/tampermokey/steam-price-converter/node_modules/rollup/dist/es/shared/rollup.js:15984:24)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async file:///G:/Code/tampermokey/steam-price-converter/node_modules/rollup/dist/es/shared/rollup.js:23754:27
    at async catchUnfinishedHookActions (file:///G:/Code/tampermokey/steam-price-converter/node_modules/rollup/dist/es/shared/rollup.js:23088:20)
    at async doBuild (file:///G:/Code/tampermokey/steam-price-converter/node_modules/vite/dist/node/chunks/dep-6b3a5aff.js:45818:26)

虽然出现了错误,但dist文件夹有构建脚本输出,且脚本能正常使用

Support multiple userscripts

export default defineConfig(async ({ command, mode }) => ({
    plugins: [
        monkey({
            entry: 'src/entry1.ts',
            userscript: {
              // ...
            },
            build: {
                fileName: 'out1.user.js',
            },
        }),

        monkey({
            entry: 'src/entry2.ts',
            userscript: {
              // ...
            },
            build: {
                fileName: 'out2.user.js',
            },
        }),
  ]

Currently only out2.user.js is written, containing both userscript headers, which does not work with tampermonkey.

`error when starting dev server: Error: EEXIST: file already exists`

Hello again!

Description

I have two vite.config files:

  • vite.config.ts: for my sveltekit website
  • userscript.vite.config.ts: for my static asset (a tampermonkey userscript using the vite-plugin-monkey pluggin)

Issue

My build and preview works, for both of the config files, but my dev doesn't work for userscript.vite.config.ts.

Content

  • userscript.vite.config.ts

    import { defineConfig } from 'vite';
    import monkey from 'vite-plugin-monkey';
    
    // https://vitejs.dev/config/
    export default defineConfig({
        plugins: [
            monkey({
                entry: 'external/script.user.ts',
                userscript: {    
                    namespace: 'https://github.com/EFRAUDE/Moodle',
                },
            }),
        ],
    });
  • here is the error i'm getting:
    REDACTED

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.