Javascript 巴别塔插件;“转换运行时”;只有在第一次编译后才能工作

Javascript 巴别塔插件;“转换运行时”;只有在第一次编译后才能工作,javascript,node.js,webpack,babeljs,yarnpkg,Javascript,Node.js,Webpack,Babeljs,Yarnpkg,我对巴贝尔有一个非常复杂的问题 当我运行warn run dev时,出现以下错误: (function (exports, require, module, __filename, __dirname) { import _slicedToArray from "babel-runtime/helpers/slicedToArray"; ^^^^^^ SyntaxErro

我对巴贝尔有一个非常复杂的问题

当我运行
warn 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)
但是如果我从
.babelrc
中的插件中删除
transformruntime
,等待它编译,然后再添加回来,它就会编译并正常工作

这是我的
.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"
      ]
    }
  }
}
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]
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
在dev.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]
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
package.json
中(我知道devdependency包含太多内容:D):


事实证明,整个问题都是几个月前在配置迁移过程中犯下的错误造成的

基本网页包配置没有像我想象的那样包含一个用于
babel polyfill
的条目,导致没有应用任何polyfill

我只需将
babel polyfill
添加到我的
条目[“供应商”]
对象中,导致我首先安装此插件的原始错误(
ReferenceError:retinatorruntime未定义
)就消失了


我仍然不明白为什么这个
转换运行时
插件导致了这个非常奇怪的问题,但我不想深入到这个兔子洞。

你是想在网页包配置中导入ESM吗?网页包配置本身只能使用CommonJS语法,因为它直接从节点运行。@SeanLarkin,否则网页包配置将保持不变,所以no@TarunLalwani你能不能也添加
package.json