Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel plugin "transform-runtime" only works after first compile

I have a very perplexing issue with Babel.

When I run yarn run dev, I get the following error:

(function (exports, require, module, __filename, __dirname) { import _slicedToArray from "babel-runtime/helpers/slicedToArray";
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:537:28)
    at loader (/home/raphael/workspace/yopp/fo/node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (/home/raphael/workspace/yopp/fo/node_modules/babel-register/lib/node.js:154:7)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Module.require (module.js:517:17)
    at require (internal/module.js:11:18)

but if I remove transform-runtime from my plugins in .babelrc, wait for it to compile then add it back, it'll compile and function correctly.

Here is my .babelrc:

{
  "presets": [
    [
      "env",
      {
        "targets": {
          "browsers": [
            "> 1% in FR",
            "safari >= 10"
          ]
        },
        "modules": false
      }
    ],
    "react",
    "flow"
  ],
  "plugins": [
    "transform-object-rest-spread",
    "transform-class-properties",
    "transform-runtime",
    "react-hot-loader/babel"
  ],
  "env": {
    "test": {
      "presets": [
        [
          "env",
          {
            "modules": "commonjs"
          }
        ],
        "react",
        "flow"
      ],
      "plugins": [
        "transform-object-rest-spread",
        "transform-class-properties",
        "transform-runtime",
        "react-hot-loader/babel"
      ]
    }
  }
}

In base.config.babel.js:

const TENANT = process.env.TENANT

if (!TENANT) throw new Error(['TENANT variable undefined!'])

const webpack = require("webpack")
const path = require('path')
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const BundleTracker = require('webpack-bundle-tracker')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const FaviconsWebpackPlugin = require('favicons-webpack-plugin')

const asset_root = path.join(__dirname, "../../assets")
const tenant_root = path.join(asset_root, `${TENANT}`)
const common_root = path.join(asset_root, "common")

const tsconfig = path.join("ts_configs", `${TENANT}_ts_config.json`)

const siteConfig = {
    name: 'fo',
    context: tenant_root,
    entry: {
        vendor: [
            'normalize.css',
            'js-cookie',
            'fine-uploader',
            'jquery',
            'jquery-menu-aim',
            'slick-carousel',
            'font-awesome/css/font-awesome.css',
            'animate.css',
            'balloon-css',
            'flatpickr',
        ],
        myEntry: 'js/whatever',
        [... other entries]

    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: 'babel-loader',
            },
            {
                test: /\.ts$/,
                use: [{
                    loader: 'babel-loader'
                }, {
                    loader: 'awesome-typescript-loader?configFileName=' + tsconfig,
                }
                ]
            },
            {
                test: /\.tsx$/,
                use: [{
                    loader: 'babel-loader'
                }, {
                    loader: 'awesome-typescript-loader?configFileName=' + tsconfig,
                }
                ]
            },
            {
                test: /\.css$/,
                use: [
                    {loader: 'style-loader'},
                    {loader: 'css-loader'},
                    {loader: 'resolve-url-loader'},
                ]
            },
            {
                test: /\.scss$/,
                use: ['css-hot-loader'].concat(ExtractTextPlugin.extract({
                        fallback: 'style-loader',
                        use: [
                            'css-loader',
                            {
                                loader: 'postcss-loader',
                                options: {
                                    sourceMap: true,
                                }
                            },
                            'resolve-url-loader',
                            {
                                loader: 'sass-loader',
                                options:
                                    {
                                        sourceMap: true,
                                        includePaths: [
                                            path.join(tenant_root, 'scss'),
                                            path.join(common_root, 'scss'),
                                            asset_root
                                        ]
                                    }
                            },
                            'css-modules-flow-types-loader',
                        ]
                    }),
                )
            },
            {
                test: /\.(png|jpe?g|gif)$/,
                use:
                    'url-loader?limit=8192&name=images/[name].[md5:hash:hex:12].[ext]',
            },
            {
                test: /\.woff2?(\?v=\d+\.\d+\.\d+)?$/,
                use:
                    'file-loader?name=fonts/[name].[md5:hash:hex:12].[ext]&mimetype=application/font-woff'
            },
            {
                test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                use:
                    'file-loader?name=fonts/[name].[md5:hash:hex:12].[ext]&mimetype=application/octet-stream'
            },
            {
                test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                use:
                    'file-loader?name=fonts/[name].[md5:hash:hex:12].[ext]'
            },
            {
                test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                use:
                    'file-loader?name=images/[name].[md5:hash:hex:12].[ext]&mimetype=image/svg+xml'
            }
        ]
    },
    resolve: {
        modules: [tenant_root, common_root, asset_root, "node_modules"],
        extensions:
            ['.js', '.ts', '.tsx'],
    }
    ,
    plugins: [
        new webpack.EnvironmentPlugin(['NODE_ENV']),
        new webpack.DefinePlugin({"TENANT": JSON.stringify(TENANT)}),
        new CleanWebpackPlugin(['static/webpack_bundles/'], {root: tenant_root}),
        new webpack.optimize.CommonsChunkPlugin({
            names: [
                'common',
                'vendor'
            ]
        }),
        new BundleTracker({filename: `webpack-stats/${TENANT}/webpack-stats.json`})
    ]
}


module.exports = [siteConfig]

In dev.config.babel.js:

const ExtractTextPlugin = require("extract-text-webpack-plugin")
const path = require('path')
const webpack = require("webpack")

const WEBPACK_DEV_SERVER_HOST = "localhost"
const WEBPACK_DEV_SERVER_PORT = process.env.WEBPACK_DEV_SERVER_PORT
if (!WEBPACK_DEV_SERVER_PORT) throw new Error(['WEBPACK_DEV_SERVER_PORT variable undefined!'])
const STATICS_PATH_SUFFIX = 'static/webpack_bundles/'

const [siteConfig] = require('./base.config.babel.js')


siteConfig.stats = {
    // fallback value for stats options when an option is not defined (has precedence over local webpack defaults)
    all: undefined,
    // Add asset Information
    assets: false,
    // Sort assets by a field
    // You can reverse the sort with `!field`.
    assetsSort: "field",
    // Add information about cached (not built) modules
    cached: false,
    // Show cached assets (setting this to `false` only shows emitted files)
    cachedAssets: false,
    // Add children information
    children: true,
    // Add chunk information (setting this to `false` allows for a less verbose output)
    chunks: false,
    // Add built modules information to chunk information
    chunkModules: false,
    // Add the origins of chunks and chunk merging info
    chunkOrigins: false,
    // `webpack --colors` equivalent
    colors: true,
    // Display the distance from the entry point for each module
    depth: false,
    // Display the entry points with the corresponding bundles
    entrypoints: false,
    // Add --env information
    env: false,
    // Add errors
    errors: true,
    // Add details to errors (like resolving log)
    errorDetails: true,
    // Add the hash of the compilation
    hash: false,
    // Set the maximum number of modules to be shown
    maxModules: 15,
    // Add built modules information
    modules: false,
    // Sort the modules by a field
    // You can reverse the sort with `!field`. Default is `id`.
    modulesSort: "field",
    // Show dependencies and origin of warnings/errors (since webpack 2.5.0)
    moduleTrace: true,
    // Show performance hint when file size exceeds `performance.maxAssetSize`
    performance: false,
    // Show the exports of the modules
    providedExports: false,
    // Add public path information
    publicPath: true,
    // Add information about the reasons why modules are included
    reasons: true,
    // Add the source code of modules
    source: true,
    // Add timing information
    timings: true,
    // Show which exports of a module are used
    usedExports: false,
    // Add webpack version information
    version: false,
    // Add warnings
    warnings: true,
}

siteConfig.plugins = siteConfig.plugins.concat([
    new ExtractTextPlugin("[name].css"),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.NamedModulesPlugin(), // Adds relative module path to hot module logging
])

siteConfig.output = {
    path: path.resolve(siteConfig.context, STATICS_PATH_SUFFIX),
    publicPath: `https://${WEBPACK_DEV_SERVER_HOST}:${WEBPACK_DEV_SERVER_PORT}/${STATICS_PATH_SUFFIX}`,
    filename: '[name].js'
}

siteConfig.devtool = 'cheap-module-source-map'
siteConfig.devServer = {
    hot: true,
    inline: true,
    historyApiFallback: true,
    host: WEBPACK_DEV_SERVER_HOST,
    port: WEBPACK_DEV_SERVER_PORT,
    https: true,
    headers: {"Access-Control-Allow-Origin": "*"},
    disableHostCheck: true,
    stats: 'minimal'
}

module.exports = siteConfig

In package.json (I know devDependencies have too much in them :D ):

{
  "name": "fo",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "dev": "NODE_ENV='development' TENANT=$TENANT webpack-dev-server --config project/webpack/dev.config.babel.js",
    "build": "NODE_ENV='production' TENANT=$TENANT webpack --config project/webpack/prod.config.babel.js --progress -p",
    "test": "jest --verbose"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/jquery": "3.3.1",
    "@types/js-cookie": "2.1.0",
    "@types/moment": "2.13.0",
    "@types/react": "16.3.12",
    "@types/slick-carousel": "1.6.32",
    "animate.css": "3.6.1",
    "awesome-typescript-loader": "3.4.1",
    "babel": "6.23.0",
    "babel-core": "6.26.0",
    "babel-jest": "22.4.3",
    "babel-loader": "7.1.4",
    "babel-plugin-transform-async-to-generator": "6.24.1",
    "babel-plugin-transform-class-properties": "6.24.1",
    "babel-plugin-transform-object-rest-spread": "6.26.0",
    "babel-plugin-transform-runtime": "6.23.0",
    "babel-polyfill": "6.26.0",
    "babel-preset-env": "1.6.1",
    "babel-preset-flow": "6.23.0",
    "babel-preset-react": "6.24.1",
    "balloon-css": "0.5.0",
    "bem-classname": "0.1.1",
    "browserslist": "3.0.0",
    "clean-webpack-plugin": "0.1.18",
    "compression-webpack-plugin": "1.1.6",
    "css-hot-loader": "1.3.2",
    "css-loader": "0.28.9",
    "css-modules-flow-types-loader": "1.1.0",
    "extract-text-webpack-plugin": "3.0.2",
    "fast-memoize": "2.3.2",
    "favicons-webpack-plugin": "0.0.7",
    "file-loader": "1.1.6",
    "file-type": "7.5.0",
    "filesize": "3.6.1",
    "fine-uploader": "5.15.6",
    "flatpickr": "4.3.2",
    "flow-bin": "0.70.0",
    "font-awesome": "4.7.0",
    "formik": "0.11.11",
    "immutability-helper": "2.6.6",
    "jest": "22.4.3",
    "jest-each": "0.3.1",
    "jquery": "3.3.1",
    "jquery-menu-aim": "1.1.0",
    "js-cookie": "2.2.0",
    "less": "3.0.0",
    "less-loader": "4.0.5",
    "moment": "2.20.1",
    "node-sass": "4.8.3",
    "normalize.css": "8.0.0",
    "postcss-cssnext": "3.1.0",
    "postcss-flexbugs-fixes": "3.3.0",
    "postcss-loader": "2.1.4",
    "postcss-reporter": "5.0.0",
    "promise-polyfill": "7.1.2",
    "react": "16.3.1",
    "react-dom": "16.3.1",
    "react-draggable": "3.0.5",
    "react-dropzone": "4.2.9",
    "react-hot-loader": "4.1.1",
    "react-modal": "3.4.2",
    "react-redux": "5.0.7",
    "read-chunk": "2.1.0",
    "redux": "4.0.0",
    "redux-devtools-extension": "2.13.2",
    "redux-saga": "0.16.0",
    "redux-saga-test-plan": "3.6.0",
    "resolve-url-loader": "2.3.0",
    "sass-loader": "7.0.1",
    "slick-carousel": "1.8.1",
    "style-loader": "0.21.0",
    "typescript": "2.7.1",
    "uglifyjs-webpack-plugin": "1.2.5",
    "url-loader": "1.0.1",
    "webpack": "3.11.0",
    "webpack-bundle-tracker": "0.3.0",
    "webpack-dev-server": "2.11.1",
    "webpack-s3-plugin": "0.9.2",
    "whatwg-fetch": "2.0.4"
  },
  "dependencies": {
    "jsonschema": "1.2.4",
    "react-dates": "16.6.1",
    "react-grid-layout": "0.16.6",
    "react-select": "1.2.1"
  }
}
like image 238
Raphaël Gomès Avatar asked Oct 17 '22 19:10

Raphaël Gomès


1 Answers

It turns out this whole issue was the result of a mistake made months ago during a config migration.

The base webpack config did NOT include an entry for babel-polyfill like I thought it did, resulting in none of the polyfills being applied.

I just had to add babel-polyfill to my entry["vendor"] object and the original error which caused me to install this plugin in the first place (ReferenceError: regeneratorRuntime is not defined) went away.

I still don't understand why this transform-runtime plugin caused this very bizarre issue, but I don't want to go deeper into that rabbit hole.

like image 66
Raphaël Gomès Avatar answered Oct 20 '22 23:10

Raphaël Gomès