简体   繁体   English

Babel插件“transform-runtime”仅在首次编译后才有效

[英]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: 当我运行yarn run dev ,我收到以下错误:

(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. 但是如果我从.babelrc插件中删除transform-runtime ,等待它编译然后再添加它,它将编译并正常运行。

Here is my .babelrc : 这是我的.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 : 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 : 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 ): package.json (我知道devDependencies中包含太多内容: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"
  }
}

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. 基础webpack配置没有像我认为的那样包含babel-polyfill polyfill的条目,导致没有应用polyfill。

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. 我只需要将babel-polyfill添加到我的entry["vendor"]对象中,并且导致我首先安装此插件的原始错误( ReferenceError: regeneratorRuntime is not defined )消失了。

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. 我仍然不明白为什么这个transform-runtime插件引起了这个非常奇怪的问题,但我不想深入研究那个兔子洞。

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

相关问题 Babel 6转换运行时:$ export不是函数 - Babel 6 transform-runtime: $export is not a function 添加@babel/transform-runtime 插件时无法读取未定义的属性“Reactstrap” - Cannot read property 'Reactstrap' of undefined When adding @babel/transform-runtime plugin Webpack 4 + Babel 7转换运行时-无效的配置对象 - Webpack 4 + Babel 7 transform-runtime - Invalid configuration object 模块构建失败:TypeError:插件“transform-runtime”没有导出插件实例 - Module build failed: TypeError: The plugin "transform-runtime" didn't export a Plugin instance 在“ Users \\\\ PhpstormProjects \\\\ easy-essay \\\\。babelrc”中指定的未知插件“ transform-runtime” - Unknown plugin “transform-runtime” specified in "Users\\PhpstormProjects\\easy-essay\\.babelrc regeneratorRuntime 未定义 Gulp Babel v7 即使在 plugin-transform-runtime 安装之后 - regeneratorRuntime is not defined Gulp Babel v7 even after plugin-transform-runtime install 在Babel中转换插件与语法插件 - Transform plugin vs Syntax plugin in Babel Cordova SQLite插件仅在首次调用时有效 - Cordova SQLite plugin only works on first call 仅使用 Babel 转换 jsx - Use Babel to transform jsx only @babel/plugin-transform-classes 是什么? - What is @babel/plugin-transform-classes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM