在 svelte/rollup 个应用程序中导入 commonjs 库

Import commonjs library in svelte/rollup app

我正在开发一个基于 svelte 的电子应用程序来学习框架(我以前没有使用 svelte 或 rollup 的经验)。

将库 modbus-serial 导入新应用程序(import ModbusRTU from "modbus-serial"const ModbusRTU = require("modbus-serial"))的 App.svelte 组件时,控制台上不断出现以下错误:

Uncaught ReferenceError: require is not defined

我错过了什么?

注意:我知道该库是为 nodejs 实现的。事实上,出于学习目的,我正在尝试移植一个以前使用 electron + react 和 electron + 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
    }
};

这个问题可能是由于在同一个项目中混用commonjs require & esm import 语句造成的。将 transformMixedEsModules 添加到 @rollup/plugin-commonjs 的配置中应该有助于解决问题:

// rollup.config.js
// ...
commonjs({
  transformMixedEsModules: true,
}),
// ...

但是请注意,我个人 运行 遇到了很多问题,这些问题将专门针对 node 的模块引入了网络。这是因为 require 在设计上是动态的,因此如果以无法静态分析的方式使用,您可能需要探索更多的 hacky 解决方法,列出 here。除此之外,节点模块的 shim、shams 和 polyfill 也不总是 100% 实现。

不过,你很幸运!由于您的目标是 electron,您可能会考虑通过主进程导入(require-ing)这些模块并使用 IPC 与其通信,请参阅 here 了解更多信息。