やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

webpack5でprivateキーワード#がエラーになった2

 前回もなったが再び。対策がたった1日で使えなくなった。萎える。webpackが5.17.0から5.18.0にあがったせいだった。さすがECMAScript界隈クソで有名なだけはある。

結論

 以下プラグインを追加することで解決する。

@babel/plugin-proposal-class-properties

原因

 classのprivate修飾子#でエラーになった。

ERROR in ./src/DomMapper.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /tmp/work/JS.Webpack.Library.DOM.Mapper.20210127140548/src/0/src/DomMapper.js: Support for the experimental syntax 'classPrivateProperties' isn't currently enabled (3:5):

  1 | import TsvLoader from './TsvLoader.js';
  2 | export default class DomMapper {
> 3 |     #path
    |     ^
  4 |     #tsv
  5 |     #keys
  6 |     constructor(path) {

Add @babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' section of your Babel config to enable transformation.
If you want to leave it as-is, add @babel/plugin-syntax-class-properties (https://git.io/vb4yQ) to the 'plugins' section to enable parsing.
...

 Add @babel/plugin-proposal-class-propertiesとある。それをインストールすれば良さそう。

手順

プロジェクト作成

mkdir my_project
cd my_project
npm init -y

インストール

npm i -D webpack webpack-cli webpack-dev-server babel-loader @babel/core @babel/preset-env @babel/plugin-proposal-class-properties @babel/plugin-proposal-private-methods

webpack.config.js

module.exports = {
  mode: "production",
  entry: "./src/DomMapper.js",
  output: {
    library: 'DomMapper',
    libraryExport: 'default',
    libraryTarget: 'var',
    filename: 'DomMapper.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: [
                // ES2020 を ES5 に変換
                "@babel/preset-env",
              ],
              plugins: [
                // private # を使えるようにする
                "@babel/plugin-proposal-class-properties",
                "@babel/plugin-proposal-private-methods",
              ],
            },
          },
        ],
      },
    ],
  },
  // ES5(IE11等)向け
  target: ["web", "es5"],
};

 全部必要。class-propertiesだけじゃダメだった。private-methodsも必要。

ビルド

npx webpack

 成功!

webpack 5.18.0 compiled successfully in 5880 ms

実行

npx webpack serve

 あとは実行するだけ。

所感

 たった一晩で使えなくなるクソっぷりに辟易とした。

対象環境

$ uname -a
Linux raspberrypi 5.4.83-v7l+ #1379 SMP Mon Dec 14 13:11:54 GMT 2020 armv7l GNU/Linux