【问题标题】:ECMAScript 2015 and gulp-babel: importing classesECMAScript 2015 和 gulp-babel:导入类
【发布时间】:2016-05-30 11:23:18
【问题描述】:

我在从其他文件导入 (ECMAScript 2015) 类时遇到问题。 我的 index.js 很短:

import {Viewer3D} from '/src/viewer3d.js';

var viewer3D = new Viewer3D();
viewer3D.foo();

并通过 index.html 中的 a 正确调用,但随后会产生:

未捕获的类型错误:无法读取未定义的属性“Viewer3D”

尝试调用 Viewer3D 构造函数时。

现在,如果我将 Viewer3D 的源代码复制到 index.js(删除导入行),一切正常。

但是如何处理多个 JS 源文件?

非常感谢您的帮助。


我的.babelrc:

 {
   "presets": ["es2015"],
   "plugins": [
           "transform-regenerator",
           "transform-object-rest-spread",
           "syntax-async-functions",
           "transform-es2015-modules-umd"
          ]
 }

我的 gulpfile.js 脚本的相关部分:

var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var gulp = require('gulp');
var runSequence = require('run-sequence');
var changed = require('gulp-changed');
var plumber = require('gulp-plumber');

...

var source_path = "./src/*.js";

...

gulp.task('build-system', function()
{
 return gulp.src( source_path )
 .pipe(sourcemaps.init())
 .pipe(babel())//Run through babel
 .pipe(sourcemaps.write('.', {
 includeContent: false,
 sourceRoot: function(file) {
 return path.relative(file.path, __dirname);
 }
 }))
 .pipe(gulp.dest("dist"));

});

我的 package.json 的相关部分:

"dependencies": {
"babel": "^6.5.2",
"browser-sync": "^2.12.10",
"del": "^2.2.0",
"gulp": "^3.9.1",
"gulp-babel": "^6.1.2",
"gulp-changed": "^1.3.0",
"gulp-live-server": "0.0.29",
"gulp-sourcemaps": "^1.6.0",
"proxy-middleware": "^0.15.0",
"run-sequence": "^1.2.1",
"three.js": "^0.77.1"
},
"devDependencies": {
"babel-plugin-transform-es2015-modules-commonjs": "^6.8.0",
"babel-plugin-transform-es2015-modules-umd": "^6.8.0",
"babel-plugin-transform-object-rest-spread": "^6.8.0",
"babel-plugin-transform-regenerator": "^6.9.0",
"babel-preset-es2015": "^6.9.0"
 }

我最小的 viewer3D.js:

export class Viewer3D {
constructor()
{
    console.warn('Called Viewer3D constructor NOW.');
}
foo()
{
    console.warn( 'foo called' );
}
}

注意: 当然,我没有在我的 gulpfile.js 脚本中捆绑源文件,它们只是编译到 dist 文件夹并通过

gulp.task('serve', ['build'], function() {
browserSync({
                online: false,
                open: false,
                port: 9010,
                server: {
                    baseDir: "dist",             
                    middleware: function (req, res, next)
                    {
                        res.setHeader('Access-Control-Allow-Origin', '*');
                        next();
                    }
                }
            });
});

注2:

我在这里找到了部分解决方案(使用 webpack):

https://github.com/tiagorg/gulp-es6-webpack-example

但是没有源映射...所以无法调试... .

【问题讨论】:

  • 你能给我们看看你的 viewer3d.js 吗?
  • 我刚刚更新了上面的代码。

标签: javascript gulp ecmascript-6 webpack babeljs


【解决方案1】:

我猜你希望导入路径是相对的而不是绝对的,将导入更改为

import {Viewer3D} from './src/viewer3d.js'

【讨论】:

  • 我做了,我的问题没有改变。
【解决方案2】:

好的,我通过以下 webpack.config.babel.js 解决了这个问题:


var path = require( 'path' );
var webpack = require( 'webpack' );

module.exports = {
    entry: {
      preload: ['babel-polyfill', './src/main.js']
    },
    cache: true,
    debug: true,
    devtool: 'source-map',
    output: {
        path: path.join(__dirname, 'dist'),
        publicPath: '../dist/',
        filename: '[name].js',
        chunkFilename: '[id].js'
    },

    resolve: {
        root: [
            path.join(__dirname, '..', 'app', 'src'),
        ],
        alias: {
            jquery$: 'jquery/jquery',
            lodash$: 'lodash/lodash',
            _$: 'lodash/lodash'
        }
    },

    resolveLoader: {
        root: [
            path.join(__dirname, 'node_modules')
        ]
    },

    module: {
        loaders: [
            {
                loader: "babel-loader",

                // Skip any files outside of your project's `src` directory
                include: [
                    path.resolve(__dirname, "src"),
                ],

                // Only run `.js` and `.jsx` files through Babel
                test: /\.jsx?$/,

                // Options to configure babel with
                query: {
                    plugins: ['transform-runtime'],
                    presets: ['es2015', 'stage-0'] //, 'react'],
                }
            },

            { test: /\.css$/, loaders: ['style/useable', 'css'] },
            { test: /[\/\\]jquery\.js$/, loader: 'exports?window.$' }
        ],
        noParse: [
            /[\/\\]jquery\.js$/
        ]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        new webpack.SourceMapDevToolPlugin({
            test:/\.js$/,
            moduleFilenameTemplate:'[absolute-resource-path]',
            fallbackModuleFilenameTemplate:'[absolute-resource-path]?[hash]',
            filename: "[file].map",
            sourceRoot:'/src/'}
        )
    ]
};

和 gulpfile.babel.js:


"use strict"

var gulp = require('gulp');
var gutil = require( 'gulp-util');
var webpack = require( 'webpack');
var webpackConfig = require( './webpack.config.babel');
var WebpackDevServer = require( 'webpack-dev-server');

gulp.task('default', ['webpack']);

gulp.task('webpack', function(callback)
{
  var myConfig = Object.create(webpackConfig);
  myConfig.plugins = [
        new webpack.optimize.DedupePlugin()
  ];

  // run webpack
  webpack(myConfig, function(err, stats)
  {
    if (err)
        throw new gutil.PluginError('webpack', err);
    gutil.log('[webpack]', stats.toString({
      colors: true,
      progress: true
    }));
    callback();
  });
});

gulp.task('server', ['webpack'], function(callback)
{
    // modify some webpack config options
    var myConfig = Object.create(webpackConfig);
    myConfig.devtool = 'eval';
    myConfig.debug = true;

    // Start a webpack-dev-server
    new WebpackDevServer(webpack(myConfig),
        {
        publicPath: '/' + myConfig.output.publicPath,
        stats: {
            colors: true
        },
        hot: true
    }).listen(9014, 'localhost', function(err)
    {
        if(err)
            throw new gutil.PluginError('webpack-dev-server', err);
        gutil.log('[webpack-dev-server]', 'http://localhost:9014/webpack-dev-server/index.html');
    });
});

并将 .babelrc 简化为:

{
  "presets": ["es2015"]
}

package.json(相关部分):

 "devDependencies": {
    "babel": "^6.5.2",
    "babel-core": "^6.9.1",
    "babel-eslint": "^6.0.4",
    "babel-loader": "^6.2.4",
    "babel-plugin-transform-runtime": "^6.9.0",
    "babel-polyfill": "^6.9.1",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-stage-0": "^6.5.0",
    "chai": "^3.5.0",
    "clean-webpack-plugin": "^0.1.9",
    "css-loader": "^0.23.1",
    "eslint": "^2.11.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.8.5",
    "gulp": "^3.9.0",
    "gulp-mocha": "^2.1.3",
    "gulp-sourcemaps": "^1.6.0",
    "gulp-util": "^3.0.7",
    "html-webpack-plugin": "^2.19.0",
    "mocha": "^2.3.3",
    "webpack": "^1.12.2",
    "webpack-dev-server": "^1.12.1"
  },
  "dependencies": {
    "babel-runtime": "^6.9.2",
    "baconjs": "^0.7.84",
    "jquery": "^2.2.4",
    "jquery-ui": "^1.10.5",
    "lodash": "^4.13.1",
    "three.js": "^0.77.1"
  }

我打电话

gulp server

用于在 chrome 中调试(它实际上不适用于 Webstorm),但如果我更改 JS 代码,则需要重新启动此脚本。

【讨论】:

    猜你喜欢
    • 2016-09-06
    • 1970-01-01
    • 2016-07-31
    • 2017-12-24
    • 2015-10-09
    • 2020-12-20
    • 2015-12-24
    相关资源
    最近更新 更多