我正在尝试使用 Babel 和 Rollup 将 jQuery 加载到我的捆绑 js 中,但由于某种原因,它不断抛出此错误消息:
src/js/components/jquery/dist/jquery.js (40:46) The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten
events.js:163
throw er; // Unhandled 'error' event
^
Error: 'default' is not exported by src/js/components/jquery/dist/jquery.js
at error (/var/www/node_modules/rollup/dist/rollup.js:170:12)
at Module.error$1 [as error] (/var/www/node_modules/rollup/dist/rollup.js:8007:2)
at Module.trace (/var/www/node_modules/rollup/dist/rollup.js:8106:9)
at ModuleScope.findDeclaration (/var/www/node_modules/rollup/dist/rollup.js:7691:22)
at Node.bind (/var/www/node_modules/rollup/dist/rollup.js:6743:29)
at /var/www/node_modules/rollup/dist/rollup.js:5291:50
at Node.eachChild (/var/www/node_modules/rollup/dist/rollup.js:5308:5)
at Node.bind (/var/www/node_modules/rollup/dist/rollup.js:5291:7)
at /var/www/node_modules/rollup/dist/rollup.js:5291:50
at Node.eachChild (/var/www/node_modules/rollup/dist/rollup.js:5305:19)
这是我的 gulp 文件。
var gulp = require('gulp');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var sass = require('gulp-sass');
var rollup = require('gulp-better-rollup')
var autoprefixer = require('gulp-autoprefixer');
var server = require('gulp-express');
var babel = require('rollup-plugin-babel');
var eslint = require('rollup-plugin-eslint');
//var commonjs = require('rollup-plugin-commonjs');
//var nodeResolve = require('rollup-plugin-node-resolve');
var inject = require('rollup-plugin-inject');
gulp.task('bundle', function() {
gulp.src('./src/js/**/*.js')
.pipe(sourcemaps.init())
// transform the files here.
.pipe(rollup({
// any option supported by Rollup can be set here.
entry: './src/js/app.js',
plugins: [
babel({
exclude: 'node_modules/**',
}),
eslint({
exclude: 'node_modules/**',
}),
inject({
include: '**/*.js',
exclude: 'node_modules/**',
jQuery: 'jquery',
$: 'jquery',
})
],
format: 'cjs',
}))
.pipe(sourcemaps.write())
.pipe(gulp.dest('./dist'));
});
当然,我让 Bower 将 jQuery 导入到 Babel 代码所在的“组件”文件夹中...
这是我的 app.js
import jQuery from 'jquery';
var $ = jQuery;
$(function(){
console.log("Hello, jQuery!");
});
我是否错误地导入了 jQuery?我需要使用更好的插件来完成此任务吗?我在网上找到的所有教程都让我进行了规避。 (这就是为什么我在我的 gulpfile 中注释掉了一些模块。)
最佳答案
Had the same issue! Quite annoying one. Took me some time to figure out.
1. npm i jquery --save-dev (for development)
2. import $ from 'jquery' where is needed
or: use import inject from '@rollup/plugin-inject';
Ex: const injectJQueryInModule = inject({
$: 'jquery',
fs: ['fs', '*'],
include: ['**/*.mjs', '**/*.js'],
exclude: 'node_modules/**',
'Module_name_to_assign': path.resolve(`${__dirname}/libs/Module_name_to_assign.js/.mjs/.ts`),
modules: { }
})
Checkout: https://github.com/rollup/rollup-plugin-inject
关于javascript - Babel + Rollup.js 导入 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43710556/