Rails webpacker возвращает SyntaxError для всех выражений JSX - PullRequest
1 голос
/ 01 апреля 2020

Хорошо, поэтому у меня есть приложение Rails, которое было обновлено до Rails 6. Весь мой код React находится в каталоге app/react, который является source_path в моем файле webpacker.yml.

rails assets:precompile работает нормально, однако, когда я запускаю ./bin/webpack локально (а также в производстве), я получаю большое количество синтаксических ошибок, подобных этой:

WARNING in ./app/react/components/manage/assets/AssetTable/AssetTable.test.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/userj/Development/rails/myapplication/app/react/components/manage/assets/AssetTable/AssetTable.test.js: Unexpected token (28:28)

  26 | describe("AssetTable", () => {
  27 |   it("renders correctly", () => {
> 28 |     const wrapper = shallow(<AssetTable />)
     |                             ^
  29 |     expect(wrapper.exists()).toBe(true)
  30 |   })
  31 |
    at Parser._raise (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:742:17)
    at Parser.raiseWithData (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:735:17)
    at Parser.raise (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:729:17)
    at Parser.unexpected (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:8757:16)
    at Parser.parseExprAtom (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:10052:20)
    at Parser.parseExprSubscripts (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9602:23)
    at Parser.parseMaybeUnary (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9582:21)
    at Parser.parseExprOps (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9452:23)
    at Parser.parseMaybeConditional (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9425:23)
    at Parser.parseMaybeAssign (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9380:21)
    at Parser.parseExprListItem (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:10718:18)
    at Parser.parseCallExpressionArguments (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9790:22)
    at Parser.parseSubscript (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9696:31)
    at Parser.parseSubscripts (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9625:19)
    at Parser.parseExprSubscripts (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9608:17)
    at Parser.parseMaybeUnary (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9582:21)
    at Parser.parseExprOps (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9452:23)
    at Parser.parseMaybeConditional (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9425:23)
    at Parser.parseMaybeAssign (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9380:21)
    at Parser.parseVar (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:11740:26)
    at Parser.parseVarStatement (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:11549:10)
    at Parser.parseStatementContent (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:11148:21)
    at Parser.parseStatement (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:11081:17)
    at Parser.parseBlockOrModuleBlockBody (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:11656:25)
    at Parser.parseBlockBody (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:11642:10)
    at Parser.parseBlock (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:11626:10)
    at Parser.parseFunctionBody (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:10634:24)
    at Parser.parseArrowExpression (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:10603:10)
    at Parser.parseParenAndDistinguishExpression (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:10221:12)
    at Parser.parseExprAtom (/Users/userj/Development/rails/myapplication/node_modules/@babel/parser/lib/index.js:9947:21)
 @ ./app/react/components sync ^\.\/.*$ ./manage/assets/AssetTable/AssetTable.test.js
 @ ./app/react/packs/server_rendering.js

Кажется, что он не распознает JSX и видит его как синтаксическая ошибка.

Вот мой файл webpacker.yml:

# Note: You must restart bin/webpack-dev-server for changes to take effect

default: &default
  source_path: app/react
  source_entry_path: packs
  public_root_path: public
  public_output_path: packs
  cache_path: tmp/cache/webpacker
  check_yarn_integrity: false
  webpack_compile_output: false

  # Additional paths webpack should lookup modules
  # ['app/assets', 'engine/foo/app/assets']
  resolved_paths: []

  # Reload manifest.json on all requests so we reload latest compiled packs
  cache_manifest: false

  # Extract and emit a css file
  extract_css: false

  static_assets_extensions:
    - .jpg
    - .jpeg
    - .png
    - .gif
    - .tiff
    - .ico
    - .svg
    - .eot
    - .otf
    - .ttf
    - .woff
    - .woff2

  extensions:
    - .jsx
    - .mjs
    - .js
    - .sass
    - .scss
    - .css
    - .module.sass
    - .module.scss
    - .module.css
    - .png
    - .svg
    - .gif
    - .jpeg
    - .jpg

development:
  <<: *default
  compile: true

  # Verifies that versions and hashed value of the package contents in the project's package.json
  check_yarn_integrity: true

  # Reference: https://webpack.js.org/configuration/dev-server/
  dev_server:
    https: false
    host: localhost
    port: 3035
    public: localhost:3035
    hmr: false
    # Inline should be set to true if using HMR
    inline: true
    overlay: true
    compress: true
    disable_host_check: true
    use_local_ip: false
    quiet: false
    headers:
      'Access-Control-Allow-Origin': '*'
    watch_options:
      ignored: '**/node_modules/**'

test:
  <<: *default
  compile: true

  # Compile test packs to a separate directory
  public_output_path: packs-test

production:
  <<: *default

  # Production depends on precompilation of packs prior to booting for performance.
  compile: false

  # Extract and emit a css file
  extract_css: true

  # Cache manifest.json for performance
  cache_manifest: true

А вот мой файл babel.config. js:

module.exports = function(api) {
  var validEnv = ['development', 'test', 'production']
  var currentEnv = api.env()
  var isDevelopmentEnv = api.env('development')
  var isProductionEnv = api.env('production')
  var isTestEnv = api.env('test')

  if (!validEnv.includes(currentEnv)) {
    throw new Error(
      'Please specify a valid `NODE_ENV` or ' +
        '`BABEL_ENV` environment variables. Valid values are "development", ' +
        '"test", and "production". Instead, received: ' +
        JSON.stringify(currentEnv) +
        '.'
    )
  }

  return {
    presets: [
      isTestEnv && [
        '@babel/preset-env',
        {
          targets: {
            node: 'current'
          }
        }
      ],
      (isProductionEnv || isDevelopmentEnv) && [
        '@babel/preset-env',
        {
          forceAllTransforms: true,
          useBuiltIns: 'entry',
          corejs: 3,
          modules: false,
          exclude: ['transform-typeof-symbol']
        }
      ]
    ].filter(Boolean),
    plugins: [
      'babel-plugin-macros',
      '@babel/plugin-syntax-dynamic-import',
      isTestEnv && 'babel-plugin-dynamic-import-node',
      '@babel/plugin-transform-destructuring',
      [
        '@babel/plugin-proposal-class-properties',
        {
          loose: true
        }
      ],
      [
        '@babel/plugin-proposal-object-rest-spread',
        {
          useBuiltIns: true
        }
      ],
      [
        '@babel/plugin-transform-runtime',
        {
          helpers: false,
          regenerator: true,
          corejs: false
        }
      ],
      [
        '@babel/plugin-transform-regenerator',
        {
          async: false
        }
      ]
    ].filter(Boolean)
  }
}

I я озадачен, почему webpacker срабатывает на этих выражениях JSX?

1 Ответ

0 голосов
/ 01 апреля 2020

Хорошо, мое решение для этого работало bundle exec rails webpacker:install:react

источник: https://github.com/rails/webpacker/issues/749#issuecomment -328074888

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...