我可以将安装了npm的库导入Web worker以使用它吗?
我需要将moment.js库用于Web worker。
它通过npm
安装到文件夹node_modules/moment
目录
我已经尝试过在worker.js文件的顶部:
importScripts('/node_modules/moment/moment.js');
但是我得到了
GET http://192.168.2.1:8100/node_modules/moment/moment.js 404 (Not Found)
有可能吗?
答案 0 :(得分:0)
是的,有可能,您已经在使用流行的捆绑器,例如webpack
或parcel
,但即使不是,也仍然可以,尽管可能不是直接来自node_modules >
// relative path to the worker from current file
const worker = new Worker('../utils/myWorker.js');
myWorker.js
// use import like you would in any other file
import moment from 'moment';
console.log(`From worker: worker started at ${moment().format('HH:mm:ss')}`);
// relative to the expected public path (have in mind any filename transforms like hashing)
const worker = new Worker('myWorker.bundle.js');
myWorker.js
// use import like you would in any other file
import moment from 'moment';
console.log(`From worker: worker started at ${moment().format('HH:mm:ss')}`);
webpack.config.js
{
entry: {
main: './src/app/main.js'
worker: './src/utils/myWorker.js',
},
output: {
path: `${ROOT_PATH}/public`,
filename: '[name].bundle.js',
}
}
// relative path to the worker from current file
import Worker from '../utils/myWorker.worker.js';
const worker = new Worker();
myWorker.worker.js
// use import like you would in any other file
import moment from 'moment';
console.log(`From worker: worker started at ${moment().format('HH:mm:ss')}`);
webpack.config.js
{
module: {
rules: [
{
test: /\.worker\.js$/,
use: { loader: 'worker-loader' }
}
]
}
}
npm install worker-loader --save-dev
worker-loader
文档https://webpack.js.org/loaders/worker-loader/ importScripts('//cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js');
console.log(`From worker: worker started at ${moment().format('HH:mm:ss')}`);
importScripts
node_modules
文件夹通常位于项目的根目录,因此您无法使用importScripts
来访问它对于将webpack用作捆绑程序的项目,只要您可以访问webpack配置并对其进行自定义,就可以调整2种webpack解决方案。
“ Webpack(作为条目)”示例实际上是从Angular CLI generated app with Web Workers借来的
{
"extends": "../generic-tsconfig.json",
"compilerOptions": {
"lib": ["esnext", "webworker"],
}
}
答案 1 :(得分:0)
截至 2020年8月12日。 通过执行以下步骤,我已成功将npm模块与CloudFlare Workers结合使用。
创建新项目:
wrangler generate your-project
cd your-project
设置“ wrangler.toml ”以使用Webpack:
name = "your-project"
type = "webpack"
account_id = "your-account-id"
workers_dev = true
route = ""
zone_id = ""
将您的npm模块导入index.js文件: 例如。
const qr = require('qr-image')
在终端/ cmd中:
wrangler publish
它会自动创建使用webpack打包的worker。 现在应该可以了。
希望这对某人有所帮助,他在Google上寻找了很长一段时间,然后才决定尝试教程并找到答案!