Синтаксическая ошибка плагина свертки CommonJS при импорте сторонних библиотек, в основном связанная с «процессом»

#reactjs #typescript #babeljs #commonjs #rollupjs

Вопрос:

Я работал над пользовательской конфигурацией свертки, которая использует проект React и объединяет js и css в index.html.
Когда я импортировал некоторые сторонние библиотеки реакций (например, материал-пользовательский интерфейс-цвет) Я столкнулся с проблемой с CommonJS, в которой говорится, что произошла синтаксическая ошибка. Из библиотек, которые я пытался установить до сих пор, слово «процесс» чаще всего является словом, на котором оно ломается. Вот журнал из проблемы с цветом материала-пользовательского интерфейса:

 [!] (plugin commonjs) SyntaxError: Unexpected token (205:28) in /Users/meyerm/Documents/GitHub/button-generator-figma-plugin/node_modules/jss/dist/jss.esm.js
node_modules/jss/dist/jss.esm.js (205:28)
203:     var newValue = value;
204:
205:     if (!options || options.process !== false) {
                                 ^
 

Я включил накопительный плагин-замену, чтобы исправить любые случаи process.env.NODE_ENV , но это, похоже, другая проблема.

Вот моя конфигурация накопительного пакета:

 import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel';
import livereload from 'rollup-plugin-livereload';
import replace from '@rollup/plugin-replace';
import { terser } from 'rollup-plugin-terser';
import postcss from 'rollup-plugin-postcss';
import html from 'rollup-plugin-bundle-html-plus';
import typescript from 'rollup-plugin-typescript';
import svgr from '@svgr/rollup';

const production = !process.env.ROLLUP_WATCH;

export default [
  /* 
  Transpiling React code and injecting into index.html for Figma  
  */
  {
    input: 'src/app/index.tsx',
    output: {
      name: 'ui',
      file: 'dist/bundle.js',
      format: 'umd',
    },
    plugins: [
      // What extensions is rollup looking for
      resolve({
        extensions: ['.jsx', '.js', '.json', '.ts', '.tsx'],
      }),

      // Manage process.env
      replace({
        preventAssignment: true,
        process: JSON.stringify({
          env: {
            isProd: production,
          },
        }),
        'process.env.NODE_ENV': JSON.stringify(production),
      }),

      typescript({ sourceMap: !production }),

      // Babel config to support React
      babel({
        presets: ['@babel/preset-react', '@babel/preset-env'],
        babelHelpers: 'runtime',
        plugins: ['@babel/plugin-transform-runtime'],
        extensions: ['.js', '.ts', 'tsx', 'jsx'],
        compact: true,
        exclude: 'node_modules/**',
      }),

      commonjs({
        include: 'node_modules/**',
      }),

      svgr(),

      // Config to allow sass and css modules
      postcss({
        extensions: ['.css, .scss, .sass'],
        modules: true,
        use: ['sass'],
      }),

      // Injecting UI code into ui.html
      html({
        template: 'src/app/index.html',
        dest: 'dist',
        filename: 'index.html',
        inline: true,
        inject: 'body',
        ignore: /code.js/,
      }),

      // If dev mode, serve and livereload
      !production amp;amp; serve(),
      !production amp;amp; livereload('dist'),

      // If prod mode, minify
      production amp;amp; terser(),
    ],
    watch: {
      clearScreen: true,
    },
  },

  /* 
  Main Figma plugin code
  */
  {
    input: 'src/plugin/controller.ts',
    output: {
      file: 'dist/code.js',
      format: 'iife',
      name: 'code',
    },
    plugins: [resolve(), typescript(), commonjs({ transformMixedEsModules: true }), production amp;amp; terser()],
  },
];

function serve() {
  let started = false;

  return {
    writeBundle() {
      if (!started) {
        started = true;

        // Start localhost dev server on port 5000 to work on the UI in the browser
        require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
          stdio: ['ignore', 'inherit', 'inherit'],
          shell: true,
        });
      }
    },
  };
}
 

Есть идеи, как я могу преодолеть это и легко импортировать сторонние библиотеки в проект?

Ответ №1:

Я рекомендую переписать конфигурацию следующим образом:

 replace({
  "process.env.isProd": production,
}),