我用一个 Webpack 配置为 JS Worker 构建一个单独的包(它必须位于单独的文件中),一切运行良好。这是 webpack 配置:
const path = require('path');
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
entry: {
worker: {
import: './assets/scripts/worker.ts',
filename: './worker_bundle.js',
}
},
output: {
'path': path.resolve(__dirname, 'static', 'js')
},
plugins: [
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
process: 'process/browser',
})
],
resolve: {
fallback: {
"assert": require.resolve('assert'),
"fs": false,
"util": require.resolve("util"),
"path": require.resolve("path-browserify")
},
extensions: ['.ts', '.js', '.json']
},
module: {
rules: [
{
test: RegExp('\\.ts$'),
use: 'ts-loader',
exclude: RegExp('node_modules')
}
]
},
externals: {
jquery: 'jQuery',
},
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: false,
terserOptions: {
format: {
comments: false,
},
},
}),
],
},
}
然后我了解了现代JS技术,叫做“Vite”。它的编译速度比 Webpack 快得多,但现在无论我做什么,捆绑包都不会在浏览器中执行。
这是构建 JS 代码的新 Vite 配置:
import path from 'path';
import commonjs from '@rollup/plugin-commonjs';
import topLevelAwait from "vite-plugin-top-level-await";
import {nodePolyfills} from "vite-plugin-node-polyfills";
module.exports = {
plugins: [
nodePolyfills({
overrides: {
fs: 'memfs'
}
}),
],
build: {
minify: false,
rollupOptions: {
input: {
regexes_worker: path.resolve(__dirname, "./assets/scripts/worker.ts"),
},
output: [
{
dir: path.resolve(__dirname, 'static/js'),
entryFileNames: 'worker_bundle.js',
globals: {
jquery: '$'
},
esModule: true
}
],
plugins: [
commonjs({
filter(id) {
if (id.includes('node_modules')) {
return true
}
}
}),
topLevelAwait(),
]
},
emptyOutDir: false
},
}
代码失败,并在开发工具控制台上打印以下错误:
Uncaught (in promise) TypeError: Function has non-object prototype 'undefined' in instanceof check
以下是使用 Vite 构建的捆绑包代码片段,其中代码失败:
function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var f = n.default;
if (typeof f == "function") {
var a = function a2() {
if (this instanceof a2 /* !! The execution fails here !! */ ) {
return Reflect.construct(f, arguments, this.constructor);
}
return f.apply(this, arguments);
};
a.prototype = f.prototype;
} else a = {};
Object.defineProperty(a, "__esModule", {
value: true
});
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function () {
return n[k];
}
});
});
return a;
}
我已经尝试过:
没有任何帮助,现在我不知道该怎么办。
我也有同样的情况,我使用了vite-plugin-commonjs。几年前我在互联网上找到了它,它解决了所有问题,但我不知道它是如何工作的。