transiled code(babel)似乎无法在浏览器中运行

时间:2018-01-27 21:16:40

标签: angularjs webpack babel babel-loader

您好我正在处理需要增强功能的现有应用。该应用程序使用angularJS,Babel,webpack构建。我努力在本地运行应用程序并最终成功运行它后,我们改变了我们如何调用基于下载的基础(如下所示)使用babel下一代javascript表示法到常规表示法(babel网站上有编译器来执行此操作)。 / p>

function filtersDirective() {
return {
 ...baseDirective(template, FiltersCtrl),
 ...{
  bindToController: {
     customers: '=',
     regions: '=',
     managers: '=',
     projects: '=',
     statuses: '=',
    },
  },
 }
}

现在问题是我能够在本地运行这个应用程序并且还能够构建捆绑文件(app.bundle.js,vendor.bundle.js,manifest.bundle.js)但是当我部署这些时文件到我的测试服务器,控制台错误如下所示。

ReferenceError: production is not defined
at dispatchXhrRequest (vendor.bundle.js:24340)
at new Promise (<anonymous>)
at xhrAdapter (vendor.bundle.js:24325)
at dispatchRequest (vendor.bundle.js:92054)
at <anonymous>
vendor.bundle.js:65932 
TypeError: Cannot read property 'map' of undefined
at https://@domain/cdn/3.2.1/vendor.bundle.js:5202:31
at https://@domain/cdn/3.2.1/vendor.bundle.js:5090:28
at f1 (https://@domain/cdn/3.2.1/vendor.bundle.js:5070:27)
at https://@domain/cdn/3.2.1/vendor.bundle.js:4920:35
at https://@domain/cdn/3.2.1/vendor.bundle.js:4920:35
at https://@domain/cdn/3.2.1/vendor.bundle.js:4920:35
at https://@domain/cdn/3.2.1/vendor.bundle.js:4672:27
at getAttributeFromProjects (https://@domain/cdn/3.2.1/app.bundle.js:117:10)
at MainController (https://@domain/cdn/3.2.1/app.bundle.js:127:21)
at invoke (https://@domain/cdn/3.2.1/vendor.bundle.js:58052:17) <div ui-view="" class="ng-scope">

My Traspiled app.bundle.js如下所示

webpackJsonp([1], {

        /***/
        101:
            /***/
            (function(module, __webpack_exports__, __webpack_require__) {

                "use strict";
                /* harmony import */
                var __WEBPACK_IMPORTED_MODULE_0_deepmerge__ = __webpack_require__(69);
                /* harmony import */
                var __WEBPACK_IMPORTED_MODULE_0_deepmerge___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_deepmerge__);


                const baseConfig = {
                    title: 'Test Dashboard',
                    dashboard: {
                        title: 'Test Report',
                        subtitle: 'Weekly Highlights'
                    },
                    header: {
                        title: 'Company Confidential',
                        nav: 'Test'
                    }
                }

                let config = baseConfig
                if (window.AppConfig) {
                    if (window.AppConfig.config) {
                        config = __WEBPACK_IMPORTED_MODULE_0_deepmerge___default.a(baseConfig, window.AppConfig.config)
                    }
                }

                const {
                    title,
                    dashboard,
                    header,
                    statusBar
                } = config
                /* harmony export (immutable) */
                __webpack_exports__["c"] = title;

                /* harmony export (immutable) */
                __webpack_exports__["a"] = dashboard;

                /* unused harmony export header */

                /* unused harmony export statusBar */


                /* harmony default export */
                __webpack_exports__["b"] = (config);


                /***/
            }),

        /***/
        222:
            /***/
            (function(module, __webpack_exports__, __webpack_require__) {

                    "use strict";
                    /* harmony export (binding) */
                    __webpack_require__.d(__webpack_exports__, "b", function() {
                        return resolve;
                    });
                    /* harmony import */
                    var __WEBPACK_IMPORTED_MODULE_0_ramda__ = __webpack_require__(36);
                    /* harmony import */
                    var __WEBPACK_IMPORTED_MODULE_0_ramda___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_ramda__);
                    /* harmony import */
                    var __WEBPACK_IMPORTED_MODULE_1_angular__ = __webpack_require__(7);
                    /* harmony import */
                    var __WEBPACK_IMPORTED_MODULE_1_angular___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_angular__);
                    /* harmony import */
                    var __WEBPACK_IMPORTED_MODULE_2__utils__ = __webpack_require__(4);
                    /* harmony import */
                    var __WEBPACK_IMPORTED_MODULE_3__services_api__ = __webpack_require__(99);
                    /* harmony import */
                    var __WEBPACK_IMPORTED_MODULE_4__appConfig_config__ = __webpack_require__(101);
                    /* harmony import */
                    var __WEBPACK_IMPORTED_MODULE_5__dashboard_html__ = __webpack_require__(479);
                    /* harmony import */
                    var __WEBPACK_IMPORTED_MODULE_5__dashboard_html___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5__dashboard_html__);
                    /* harmony reexport (default from non-hamory) */
                    __webpack_require__.d(__webpack_exports__, "c", function() {
                        return __WEBPACK_IMPORTED_MODULE_5__dashboard_html___default.a;
                    }); 

与以前版本的app.bundle.js有很大的不同,它位于prod服务器上,如下所示

webpackJsonp([1], {

        /***/
        10:
            /***/
            (function(module, exports, __webpack_require__) {

                    "use strict";


                    Object.defineProperty(exports, "__esModule", {
                        value: true
                    });
                    exports.getWebpartData = undefined;

                    var _keys = __webpack_require__(124);

                    var _keys2 = _interopRequireDefault(_keys);

                    var _deepmerge = __webpack_require__(76);

                    var _deepmerge2 = _interopRequireDefault(_deepmerge);

                    var _utils = __webpack_require__(4);

                    var _majorMilestones = __webpack_require__(501);

                    var _majorMilestones2 = _interopRequireDefault(_majorMilestones);

                    var _budget = __webpack_require__(502);

                    var _budget2 = _interopRequireDefault(_budget);

                    var _projectRisksAndIssues = __webpack_require__(503);

                    var _projectRisksAndIssues2 = _interopRequireDefault(_projectRisksAndIssues);

                    var _actionItems = __webpack_require__(504);

                    var _actionItems2 = _interopRequireDefault(_actionItems);

                    var _keyDates = __webpack_require__(505);

                    var _keyDates2 = _interopRequireDefault(_keyDates);

                    var _gantt = __webpack_require__(506);

                    var _gantt2 = _interopRequireDefault(_gantt);

                    var _statusBar = __webpack_require__(507);

                    var _statusBar2 = _interopRequireDefault(_statusBar);

                    var _angular = __webpack_require__(6);

                    var _angular2 = _interopRequireDefault(_angular);

                    function _interopRequireDefault(obj) {
                        return obj && obj.__esModule ? obj : {
                            default: obj
                        };
                    }

下面是我的package.json文件供参考

{
"name": "pmrdashboard",
"version": "3.2.1",
"dependencies": {
    "@cgross/angular-notify": "2.5.1",
    "angular": "1.4.2",
    "angular-bootstrap": "~0.12.2",
    "angular-chart.js": "^1.0.1",
    "angular-gantt": "^1.2.13",
    "angular-google-chart": "^0.1.0",
    "angular-messages": "~1.4.2",
    "angular-moment": "1.0.1",
    "angular-pubsub": "^0.2.0",
    "angular-resource": "~1.4.2",
    "angular-sanitize": "~1.4.2",
    "angular-strap": "^2.3.9",
    "angular-toastr": "~1.5.0",
    "angular-ui-router": "~0.2.15",
    "animate.css": "~3.4.0",
    "axios": "^0.16.2",
    "babel-cli": "^6.24.1",
    "babel-core": "^6.24.1",
    "babel-polyfill": "^6.23.0",
    "babel-runtime": "^6.23.0",
    "bootstrap-sass": "3.3.7",
    "chart.js": "2.1.0",
    "deepmerge": "^1.3.2",
    "echo-loader": "0.0.1",
    "jquery": "~2.1.4",
    "lodash": "^4.13.1",
    "moment": "2.10.6",
    "ngsticky-puemos": "^0.0.4",
    "node-sass": "4.5.3",
    "ramda": "^0.22.1"
},
"scripts": {
    "dev": "babel-node scripts/cli.js dev",
    "serve": "babel-node scripts/cli.js serve",
    "build": "babel-node scripts/cli.js build --upload=false --plugins dynamic-import-node",
    "deploy": "babel-node scripts/cli.js build",
    "serve:prod": "babel-node scripts/cli.js serve:prod",
    "serve:optimize": "babel-node scripts/cli.js serve:prod --optimize=true",
    "serve:cdn": "babel-node scripts/cli.js serve:prod --usecdn=true"
},
"devDependencies": {
    "babel-eslint": "^7.2.3",
    "babel-loader": "^7.0.0",
    "babel-plugin-angularjs-annotate": "^0.7.0",
    "babel-plugin-dynamic-import-node": "^1.0.2",
    "babel-plugin-external-helpers": "^6.22.0",
    "babel-plugin-transform-object-rest-spread": "^6.23.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.5.1",
    "chalk": "^1.1.3",
    "clean-webpack-plugin": "0.1.16",
    "cross-env": "^5.1.3",
    "css-loader": "0.28.1",
    "eslint": "2.13.1",
    "eslint-config-angular": "^0.5.0",
    "eslint-plugin-angular": "^2.4.0",
    "execa": "^0.6.3",
    "exports-loader": "0.6.4",
    "express": "^4.15.3",
    "extract-text-webpack-plugin": "2.1.0",
    "file-loader": "0.11.1",
    "fs-extra": "^3.0.1",
    "html-loader": "0.4.5",
    "html-webpack-harddisk-plugin": "0.1.0",
    "html-webpack-plugin": "2.28.0",
    "http-proxy-middleware": "*",
    "http-server": "^0.10.0",
    "image-webpack-loader": "3.3.1",
    "imports-loader": "0.7.1",
    "jshint-loader": "^0.8.4",
    "raw-loader": "0.5.1",
    "resolve-url-loader": "2.0.2",
    "rollup": "^0.43.0",
    "rollup-plugin-babel": "^2.7.1",
    "rollup-plugin-node-resolve": "^3.0.0",
    "sass-loader": "6.0.5",
    "shelljs": "^0.7.7",
    "ssh-webpack-plugin": "^0.1.7",
    "style-loader": "0.17.0",
    "svg-loader": "0.0.2",
    "url-loader": "0.5.8",
    "webpack": "3.0.0",
    "webpack-dev-server": "^2.5.0",
    "yargs": "^8.0.1"
},
"engines": {
    "node": ">=0.10.0"
}
}

webpack配置文件:它是.babelrc,dev.js,server.js,prod.js,share.js的文件夹,下面是share.js文件

const path = require('path')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {
   rm
} = require('shelljs')
const pkg = require('../package.json')
const webpack = require('webpack')

const baseChunks = ['config', 'app']

const basePlugins = (chunks, enableHtml) => {
const html = enableHtml ?
    [
        new HtmlWebpackPlugin({
            title: 'PMR Client',
            filename: './index.html',
            template: './src/client/index.ejs',
            chunksSortMode: (a, b) => chunks.indexOf(a.names[0]) - chunks.indexOf(b.names[0]),
            alwaysWriteToDisk: true,
            env: process.env.NODE_ENV || 'development',
        }),
        new HtmlWebpackHarddiskPlugin(),
    ] :
    []
return [
    new ExtractTextPlugin('style.css'),
    ...html,
    new webpack.ProvidePlugin({
        'window.jQuery': 'jquery',
    }),
    new webpack.optimize.ModuleConcatenationPlugin(),
]
}

const baseEntries = {
app: './src/app/index.js',
config: `./clients/${process.env.CLIENT}/config.js`,
}

const baseOutput = () => {
const output = {
    path: path.join(__dirname, `../dist/cdn/${pkg.version}`),
    filename: '[name].bundle.js',
}
if (process.env.NODE_ENV === 'production' && process.env.UPLOAD === 'true') {
    output['publicPath'] = `//streamlinedoffice.com/pmr/cdn/${pkg.version}/`
}
return output
}

const sourceMap = (process.env.NODE_ENV === 'production') ? '' : 'sourceMap'

const getBaseConfig = ({
plugins = [],
chunks = [],
entries = baseEntries,
enableHtml = false
} = {}) => {
rm('-rf', path.resolve(__dirname, '../dist'))

const ch = [...baseChunks, ...chunks]
return {
    entry: entries,
    output: baseOutput(),
    target: 'web',
    devtool: 'cheap-module-eval-source-map',
    plugins: [...basePlugins(ch, enableHtml), ...plugins],
    module: {
        rules: [{
                test: /\.html$/,
                use: [{
                    loader: 'html-loader',
                    options: {
                        minimize: true,
                        root: '../src/assets/images',
                    },
                }, ],
            },
            {
                test: [/src\/app.*\.js$/, /client.*\.js$/],
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    // loader:'echo-loader',
                },
            },
            {
                test: [/\.css$/, /\.scss$/],
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader', `sass-loader?${sourceMap}`],
                }),
            },
            {
                test: /bootstrap-sass\/assets\/javascripts\//,
                use: 'imports-loader?jQuery=jquery'
            },
            // Font Definitions
            {
                test: /\.svg$/,
                loader: 'url-loader?limit=65000&mimetype=image/svg+xml&name=public/fonts/[name].[ext]',
            },
            {
                test: /\.woff$/,
                loader: 'url-loader?limit=65000&mimetype=application/font-woff&name=public/fonts/[name].[ext]',
            },
            {
                test: /\.woff2$/,
                loader: 'url-loader?limit=65000&mimetype=application/font-woff2&name=public/fonts/[name].[ext]',
            },
            {
                test: /\.[ot]tf$/,
                loader: 'url-loader?limit=65000&mimetype=application/octet-stream&name=public/fonts/[name].[ext]',
            },
            {
                test: /\.eot$/,
                loader: 'url-loader?limit=65000&mimetype=application/vnd.ms-fontobject&name=public/fonts/[name].[ext]',
            },
            {
                test: /\.png$/,
                use: {
                    loader: 'url-loader?limit=8192',
                },
            },
            {
                test: /\.(jpe?g|gif)$/i,
                use: [
                    'file-loader?hash=sha512&digest=hex&publicPath=../&name=./img/[hash].[ext]',
                    {
                        loader: 'image-webpack-loader',
                        query: {
                            gifsicle: {
                                interlaced: false,
                            },
                            progressive: true,
                            optipng: {
                                optimizationLevel: 7,
                            },
                            bypassOnDebug: true,
                        },
                    },
                ],
            },
        ],
    },
}
}
module.exports = getBaseConfig

以下是用于构建app.bundle.js,vendor.bundle.js和manifest.bundle.js文件的脚本(此文件位于scripts / cmds / prod.js上)

import {
echo,
head,
execStrict,
ls,
copy,
rmdir,
mkdir
} from '../utils'
import fs from 'fs-extra'
import path from 'path'
import {
rollup
} from 'rollup'
import resolve from 'rollup-plugin-node-resolve'
import babel from 'rollup-plugin-babel'

const compiler = client =>
rollup({
    entry: `./clients/${client}/config.js`,
    plugins: [
        resolve(),
        babel({
            exclude: 'node_modules/**',
            babelrc: false,
            presets: [
                ['env',
                    {
                        modules: false,
                        targets: {
                            browsers: [
                                "last 3 versions",
                                "Explorer 9",
                            ],
                        },
                    },
                ],
            ],
            plugins: ['external-helpers'],
            externalHelpers: true
        }),
    ],
}).then(bundle =>
    bundle.write({
        format: 'cjs',
        dest: path.join(__dirname, `../../.tmpClients/${client}/config.js`),
    })
)

const getClients = () =>
fs
.readdirSync('./clients')
.filter(file => fs.lstatSync(path.join('./clients', file)).isDirectory())

const handleCommand = async ({
upload = true,
optimize = true
}) => {
echo(head('Building clients...'))
const clients = getClients()
mkdir('./.tmpClients')

const promises = clients.map(client => {
    compiler(client)
})

await Promise.all(promises)

echo(head('Run production build'))

await execStrict(
    `cross-env UPLOAD=${upload} OPTIMIZE=${optimize} NODE_ENV=production webpack --config webpack/prod.js --progress --colors --define process.env.NODE_ENV="'production'"`
)

echo(head('Copying config files to clients'))
ls('./.tmpClients').forEach(client => {
    copy({
        origin: `./.tmpClients/${client}/*.js`,
        dest: `./dist/clients/${client}`,
    })

    copy({
        origin: `./dist/clients/${client}/index.html`,
        dest: `./dist/clients/${client}/default.aspx`,
    })

    copy({
        origin: './src/client/favicon.ico',
        dest: `./dist/clients/${client}/`,
    })
})
rmdir('./.tmpClients')


}

exports.command = 'build'
exports.describe = 'Create a production build'
exports.handler = handleCommand
exports.builder = {
upload: {
    describe: 'Upload the production files to the cdn',
    type: 'boolean',
    default: true,
},
optimize: {
    describe: 'Toggle the production optimizations, useful to check the production build as development',
    type: 'boolean',
    default: true,
},
}
下面的

是webpack文件夹中的.babelrc:

{
      "presets": ["env"],
      "plugins": ["transform-object-rest-spread", "dynamic-import-node"]
}

下面.babelrc与webpack文件夹

处于全局相同的级别
{
  "presets":  [
    ["env", {
      "targets": {
        "browsers": ["last 3 versions","Explorer 9"]
      }
    }]
  ],
  "plugins": ["transform-runtime", "transform-object-rest-spread", 
["angularjs-annotate", {
    "explicitOnly": true
  }]]
}

如果遇到类似问题的任何人都知道如何解决它,请分享您的输入。任何帮助深表感谢。感谢

0 个答案:

没有答案