首页 > 解决方案 > SyntaxError:导入声明只能出现在带有 gulp 网页的模块的顶层

问题描述

不是这个的重复它与这个相似,但答案从未正确给出。

试图分解一个三个js的网页,来理解它。但我收到上述错误。我意识到我需要捆绑我的 JS 并且我正在尝试做同样的事情。

gulp.task('compile', gulp.series('copy'), function() {
    var bsfy = watchify(browserify('./app/index.js', {
        debug: true,
        cache: {},
        packageCache: {}
    }));
    return bsfy.bundle()
    .on('error', notify.onError({
        'title': "Error when building Browserify",
        'subtitle': "<%= error.fileName %>",
        'message': "<%= error.message %>"
    }))
    .pipe(source('index.js'))
    .pipe(gulp.dest('./dist/'));
});

我的 gulpfile 的其余部分设置为

gulp.task('copy', function(done){ 
    gulp.src('./app/**')
    .pipe(gulp.dest('./dist/'));
    done();
});
gulp.task('watch', function() {
    gulp.watch('./app/**', ['compile']);
    browserSync.watch([
        './dist/**',
    ], {
        ignored: '**/*.map'
    }).on('change', browserSync.reload);
})

gulp.task('browser', function() {
    browserSync.init({
        port: 1234,
        watch: true,
        watchOptions: {
            ignoreInitial: true,
            ignored: '**/*.map'
        },
        files: ['./dist/**'],
        ui: false,
        server: {
            baseDir: "./dist/"
        }
    });
    gulp.series('watch');
});

gulp.task('default', gulp.series('compile', 'browser'));

但我仍然得到

SyntaxError: import declarations may only appear at top level of a module

我的 gulp 命令正确启动本地网络服务器

[15:58:50] Using gulpfile ~\OneDrive\Desktop\Programs\enigma\gulpfile.js
[15:58:50] Starting 'default'...
[15:58:50] Starting 'compile'...
[15:58:50] Starting 'copy'...
[15:58:50] Finished 'copy' after 9.34 ms
[15:58:50] Finished 'compile' after 11 ms
[15:58:50] Starting 'browser'...
[Browsersync] Access URLs:
 -----------------------------------
    Local: http://localhost:1234
 External: http://172.17.59.161:1234
 -----------------------------------
[Browsersync] Serving files from: ./dist/
[Browsersync] Watching files...

我的 app.js 配置为在第二行导入 gsap

'use strict';
import 'gsap';
import app from './app';
...

我在我的 index.html 上导入 index.js 作为

<script src="./index.js" type="text/javascript"></script>

标签: javascripthtmlnode.jsgulpsyntax-error

解决方案


推荐阅读