简体   繁体   中英

Babel (gulp-babel) Uncaught ReferenceError: require is not defined

I'm using gulp , gulp-babel , which is causing an error.
I don't know how I can use module (ES6) because, when I try to import another file into this, it shows me this message:

Uncaught ReferenceError: require is not defined

I know the problem is after code has transpiled, because, I tried linking to code that's not transpiled, and it works perfectly.

These are my files.

app.js *(Where I want to use import to get another module...)

Note: Using require from CommonJS project, also does not work.

import a from "./comun.js"; //This doesn't work
class Player{
    contructor(){...}
}

comun.js (Where i want to get a const from)

export const a = 1;

index.html (Html file) (File transpiled)

<script src="./dist/js/app.js" type="module"></script>

And this is my gulpfile.babel.js (It's working perfectly)

const gulp = require ('gulp');
const babel = require('gulp-babel');
function transpileToES5() {
    return  gulp.src('./assets/js/*.js')
    .pipe(babel())
    .pipe(gulp.dest('./dist/js/'));
}

gulp.task('default', function () {
    return gulp.watch(['./assets/js/*.js'], transpileToES5)
});

And finally. This is my .babelrc file (I tried with commonjs, systemjs, amd... Nothing works )

{
    "presets" : ["@babel/env"],
    "plugins": ["transform-es2015-modules-commonjs"]
}

This is the Error:
在浏览器上显示错误的捕获

This is the line causing the error:
在浏览器上显示错误行的捕获

I had exactly the same problem. You have to use Browserify + Babelify + Gulp. More info here:

https://medium.com/@hey.aaron/getting-import-export-working-es6-style-using-browserify-babelify-gulp-5hrs-of-life-eca7786e44cc

    return browserify({
    entries: ['./src/js/index.js'],
    debug: true,
    transform: [
      babelify.configure({ presets: ['@babel/preset-env'] }),
    ],
  })
    .bundle()
    .pipe(source('index.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({ loadMaps: true }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM