简体   繁体   English

用于较新节点目标的 babel7 配置在 `import` 语句中失败

[英]babel7 config for newer node targets fails on `import` statements

When building my node api with webpack and babel and node v12.13, I'm getting this error:使用 webpack 和 babel 以及 node v12.13 构建我的node api 时,我收到此错误:

Module build failed (from /../node_modules/babel-loader/lib/index.js):TypeError: /../src/handler.js:
Property name expected type of string but got null

This seems to be related to ES6 import statements in the source files.这似乎与源文件中的 ES6 import语句有关。

Below is the config I have ended up with.下面是我最终得到的配置。 Based on this, the only thing that makes it work is setting { targets: { node: 6 }} but I need to set target to v12.基于此,使其工作的唯一方法是设置{ targets: { node: 6 }}但我需要将 target 设置为 v12。

I haven't found a relevant discussion.我还没有找到相关的讨论。 What could be the reason for this issue?这个问题的原因是什么? This is a package inside a yarn workspace , but I think this shouldn't matter.这是一个yarn workspace内的包,但我认为这无关紧要。

.babelrc: (located in api package root, same result with a .babelrc.js or babel.config.json ) .babelrc:(位于 api 包根目录,与.babelrc.jsbabel.config.json结果相同)

  comments: false,
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current'
        }
      }
    ]
  ],
  plugins: [
    '@babel/plugin-transform-runtime',
    '@babel/plugin-transform-regenerator',
    '@babel/plugin-transform-modules-commonjs',
    '@babel/plugin-proposal-object-rest-spread',
    'source-map-support'
  ]

webpack.config.js: webpack.config.js:

const path = require('path')
const nodeExternals = require('webpack-node-externals')
const slsw = require('serverless-webpack')
const webpack = require('webpack')

module.exports = {
  entry: slsw.lib.entries,
  target: 'node',
  mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
  optimization: {
    minimize: false
  },
  performance: {
    hints: false
  },
  devtool: slsw.lib.webpack.isLocal ? 'eval-source-map' : 'none',
  externals: [
    nodeExternals({ whitelist: ['workspace-package-b'] }),
    nodeExternals({
      modulesDir: path.resolve(__dirname, '../../node_modules'),
      whitelist: ['workspace-package-b']
    })
  ],
  module: {
    rules: [
      {
        test: /\.graphql$/,
        loader: 'graphql-tag/loader'
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ['imports-loader?graphql', 'babel-loader']
      }
    ]
  },
  output: {
    libraryTarget: 'commonjs2',
    path: path.join(__dirname, '.webpack'),
    filename: '[name].js',
    sourceMapFilename: '[file].map'
  },
  plugins: [new webpack.DefinePlugin({ 'global.GENTLY': false })]
}

Relevant package.json:相关 package.json:

(dependencies)
"babel-runtime": "^6.26.0",
"core-js": "^3.6.4",
(devDependencies)
"@babel/core": "^7.9.0",
"@babel/plugin-proposal-object-rest-spread": "^7.4.4",
"@babel/plugin-transform-modules-commonjs": "^7.9.0",
"@babel/plugin-transform-regenerator": "^7.8.7",
"@babel/plugin-transform-runtime": "^7.9.0",
"@babel/preset-env": "^7.9.0",
"babel-jest": "24.9.0",
"babel-loader": "8.1.0",
"babel-plugin-source-map-support": "^2.0.1",
"jest": "24.9.0",
"webpack": "4.19.1",
"webpack-node-externals": "^1.7.2"

that form of .babelrc config file is deprecated, instead of that use the one babeljs recommends babel.config.js , with this "form" if u wanna call it like that, there is one cool feature.这种形式的.babelrc配置文件已被弃用,而不是使用 babeljs 推荐的babel.config.js ,如果你想这样称呼它,使用这种“形式”,有一个很酷的功能。 you get a param that has quite a few tricks you can use.你会得到一个参数,它有很多你可以使用的技巧。

... BTW you are missing @babel/cli, @babel/runtime @babel/core, babel-core@7.0.0-bridge.0 ... 顺便说一句,你错过了@babel/cli、@babel/runtime @babel/core、babel-core@7.0.0-bridge.0

    "use strict";

    module.exports = function (api) {
      const {NODE_ENV} = process.env;

      api.cache(()=>NODE_ENV)
      api.env()

      if (NODE_ENV === "development") {
         api.async();
      }

      return {
    plugins: [],
    presets: []
      }
    }

It turns out the gist is this:事实证明,要点是这样的:

I had initially added these plugins because jest complained about seeing an import .我最初添加了这些插件,因为 jest 抱怨看到一个import

    '@babel/plugin-transform-runtime',
    '@babel/plugin-transform-regenerator',
    '@babel/plugin-transform-modules-commonjs'

But then I realized that this now broke my normal webpack build.但后来我意识到这现在破坏了我正常的 webpack 构建。

The two issues related to this seem to be:与此相关的两个问题似乎是:

webpack 2 offers native support for ES modules. webpack 2 为 ES 模块提供原生支持。 However, Jest runs in Node, * and thus requires ES modules to be transpiled to CommonJS modules.但是,Jest 运行在 Node, * 中,因此需要将 ES 模块转换为 CommonJS 模块。

The following .babelrc.js resolves this issue for me:以下.babelrc.js为我解决了这个问题:

/*
 * webpack 2 offers native support for ES modules. However, Jest runs in Node,
 * and thus requires ES modules to be transpiled to CommonJS modules.
 *
 * Reads:
 * https://jestjs.io/docs/en/webpack
 * https://github.com/facebook/jest/issues/6229
 *
 */
const configByEnv = isTest => {
  // https://babeljs.io/docs/en/babel-preset-env#targets
  // "Sidenote, if no targets are specified, @babel/preset-env will transform
  // all ECMAScript 2015+ code by default."
  const targets = isTest ? {} : { node: 'current' }

  const addPlugins = isTest
    ? [
        '@babel/plugin-transform-runtime',
        '@babel/plugin-transform-regenerator',
        '@babel/plugin-transform-modules-commonjs'
      ]
    : []

  return {
    comments: false,
    presets: [['@babel/preset-env', { targets }]],
    plugins: [
      ...addPlugins,
      '@babel/plugin-proposal-object-rest-spread',
      'source-map-support'
    ]
  }
}

module.exports = api => {
  const isTest = api.env('test')

  return configByEnv(isTest)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 javascript 中配置 babel7 以支持从 `export default` 中的 `import {}` - How to configure babel7 to support `import {}` from `export default` in javascript 如何使Gulp在项目的根目录中读取Babel7的babel.config.js? - How to make Gulp read babel.config.js of Babel7 in the root of the project? 如何将Babel7配置文件路径传递给mocha和gulp-mocha? - How to pass Babel7 config file path to mocha and gulp-mocha? 将polyfill作为带有babel-preset-env的import语句或将它们添加到webpack.config.js的条目中是否更好? - Is it better to have polyfills as import statements with babel-preset-env or add them in entries at webpack.config.js? Babel编译的JS无法导入相对路径 - Babel compiled JS fails to import relative paths 当 babel cli 正常工作时,babel-node 失败 - babel-node fails when babel cli works correctly ES6模块,babel / webpack。 导入/导出语句不起作用 - ES6 modules, babel/webpack. Import/Export statements not working 在Babel和Webpack中使用异步等待和动态导入语句 - Using async await and dynamic import statements with Babel and Webpack 如何使用 babel 预设 env 保留动态导入语句? - How can I preserve dynamic import statements with babel preset env? babel-node无法在node_modules中需要jsx文件 - babel-node fails to require jsx file in node_modules
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM