require is not defined error with browserify

前端 未结 4 1320
余生分开走
余生分开走 2020-12-02 17:17

I\'m new to browserify and trying to load npm modules in browser but I\'m getting the following error:

Uncaught ReferenceError: require is not defined

4条回答
  •  广开言路
    2020-12-02 17:55

    It seems that to run a script like that you have to use standalone on the bundle.

    browserify main.js --standalone Bundle > bundle.js
    

    After that you should have window.Bundle in bundle.js.
    So at that point you should be able to access from script.js.

    if you are using grunt

    If you are using grunt install grunt-browserify.

    npm install grunt-browserify --save-dev
    

    And then on grunt.js Gruntfile:

    // Add the task
    grunt.loadNpmTasks('grunt-browserify');
    
    // Add the configuration:
    browserify: {
        dist: {
            options: {
                // uncomment if you use babel
                // transform: [
                //     ["babelify", { "presets": ["env"] }]
                // ],
                browserifyOptions: {
                    standalone: 'Bundle'
                }
            },
            files: {
               "bundle.js": ["main.js"]
            }
        }
    },
    

    if you are using gulp

     // on your build task
     var bundled = browserify('main.js', { standalone: 'Bundle' })
                   .bundle()
                   .pipe(source('bundle.js'))
                   .pipe(gulp.dest(outDir));
    

    See here for Chart.js gulp file.

    if you are using babel

    If you are using babel and es6 probably you are exporting your Bundle class.

    // you should have something like that 
    
    class Bundle {
        ...
    
    }
    
    export default Bundle;
    

    So because of babel now to use Bundle you should use Bundle.default and so:

    // in script.js
    var bundle = new Bundle.default();
    

    To avoid this syntax you can override Bundle with Bundle.default.

    At the end of bundle.js insert:

    window.Bundle = window.Bundle.default;
    

    So now on you'll have :

    // in script.js
    var bundle = new Bundle();
    

    Sources

    Standalone browserify builds

提交回复
热议问题