我正在开发一个基于svelte的电子应用程序来学习这个框架(我以前没有使用svelte或rollup的经验)。
在将modbus-serial库导入到新应用(import ModbusRTU from "modbus-serial"
或const ModbusRTU = require("modbus-serial")
)的App.svelte组件中时,我在控制台上不断收到以下错误:
Uncaught ReferenceError: require is not defined
我遗漏了什么?
注意:我知道这个库是为nodejs实现的。事实上,出于学习目的,我正在尝试移植到svelte,这是一个以前使用电子+ react和电子+ vue构建的IoT应用程序。使用react和vue,我在导入库时没有遇到任何问题。
在我的rollup.config.js下面:
import svelte from 'rollup-plugin-svelte';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import sveltePreprocess from 'svelte-preprocess';
import typescript from '@rollup/plugin-typescript';
import css from 'rollup-plugin-css-only';
const production = !process.env.ROLLUP_WATCH;
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
process.on('SIGTERM', toExit);
process.on('exit', toExit);
}
};
}
export default {
input: 'src/main.ts',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
svelte({
preprocess: sveltePreprocess({ sourceMap: !production }),
compilerOptions: {
// enable run-time checks when not in production
dev: !production
}
}),
// we'll extract any component CSS out into
// a separate file - better for performance
css({ output: 'bundle.css' }),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
typescript({
sourceMap: !production,
inlineSources: !production
}),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};
发布于 2021-10-31 16:56:08
这个问题可能是由于在同一个项目中混用了commonjs require
和esm import
语句造成的。在@rollup/plugin-commonjs
的配置中添加transformMixedEsModules
应该会在一定程度上解决这个问题:
// rollup.config.js
// ...
commonjs({
transformMixedEsModules: true,
}),
// ...
但是,请注意,我个人遇到了大量的问题,将专门针对节点的模块带到了web上。这是因为require
在设计上是动态的,因此如果以不能静态分析的方式使用,您可能需要探索更多棘手的解决方法,列出here。除此之外,节点模块的填充、伪装和多边形填充也不总是100%实现的。
然而,你是幸运的!由于您的目标是electron
,因此您可以考虑通过主进程导入(require
-ing)这些模块&改为使用IPC与其通信,有关更多信息,请参阅here。
https://stackoverflow.com/questions/69762143
复制相似问题