Webpack加载器配置错误与类方法this指向问题求助
解决Gulp+Webpack+Babel构建中的两个问题
问题1:类箭头函数引发Webpack Loader错误
问题分析
在类中使用箭头函数作为类方法(如init = () => {})后,Webpack提示缺少合适的loader。这是因为当前构建流程中,gulp-babel先转译文件,但后续Webpack处理时,流程衔接出现冲突,导致转译不彻底或未被正确识别。
解决方案
调整构建流程,让Webpack内部通过Babel Loader处理JS转译,替代单独的gulp-babel调用,确保转译与打包流程统一:
- 安装必要依赖(未安装时执行):
npm install babel-loader @babel/core @babel/preset-env @babel/plugin-proposal-class-properties --save-dev
- 修改gulpfile中的js任务,移除
gulp-babel的pipe,将Babel配置整合到Webpack的loader规则中:
// js task const js = () => { return src('src/**/*.js') .pipe(webpack({ mode: 'development', devtool: 'inline-source-map', module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: [['@babel/env']], plugins: [["@babel/plugin-proposal-class-properties", { "loose": true }]] } } } ] } })) .pipe(mode.development( sourcemaps.init({ loadMaps: true }) )) .pipe(rename('scripts.js')) .pipe(mode.production( terser({ output: { comments: false }}) )) .pipe(mode.development( sourcemaps.write() )) .pipe(dest('dist/scripts')) .pipe(mode.development( browserSync.stream() )); }
Webpack会直接通过Babel Loader处理所有JS文件,类箭头函数语法将被正确转译,不再触发loader错误。
问题2:普通方法中this指向错误导致TypeError
问题分析
改回普通类方法后,update方法中调用window.requestAnimationFrame(this.update)时,this默认指向全局window,而非类实例,因此访问this.clock会提示“无法读取undefined的clock属性”。
解决方案
以下三种方式均可修复this指向问题:
方案1:构造函数中绑定this
在Experience类的构造函数末尾添加:
this.update = this.update.bind(this);
方案2:箭头函数包裹回调
修改update方法中的requestAnimationFrame调用:
window.requestAnimationFrame(() => this.update());
方案3:使用类箭头函数定义update(需先解决问题1)
直接将update改为箭头函数方法,自动绑定类实例的this:
update = () => { this.time = this.clock.getElapsedTime(); this.updateItems(); this.renderer.render(this.scene, this.camera); window.requestAnimationFrame(this.update); console.log(this.clock.getElapsedTime()) };
推荐方案1(兼容性好)或方案3(写法简洁)。
内容的提问来源于stack exchange,提问作者Bla Tor
相关产品推荐
相关产品推荐

