【发布时间】:2025-11-24 07:25:02
【问题描述】:
我是 Webpack 的新手,在 this tutorial 之后遇到了问题。
似乎 webpack.config.js 没有正确设置 babel-loader 但我不确定。在控制台中我看到以下错误:
bundle.js:49 Uncaught SyntaxError: Unexpected token import
指的是我的index.js 的import sortBy from 'lodash/collection/sortBy'; 行。所以我认为这是一个 babel 转译问题(不允许 ES6 的 import 语法?)
这是完整的index.js 文件
import sortBy from 'lodash/collection/sortBy';
import {users} from './users';
import {User} from './User';
sortBy(users, 'name')
.map(user => {
return new User(user.name, user.age);
})
.forEach(user => {
console.log(user.display);
});
而webpack.config.js 看起来像这样:
module.exports = {
entry: './src/index.js',
output: {
path: './public/',
filename: 'bundle.js'
},
devServer: {
contentBase: './public/'
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel'}
]
}
}
我搜索了其他看起来与问题here 和here 相关的问题,并四处搜索,但还没有找到解决方案或我收到错误的原因。也许本教程已过时。任何如何解决此问题的指导将不胜感激!
更新
按照 Alexandre Thebaldi 下面发布的答案中概述的步骤解决了特定的 babel 加载错误。
但是,发生了一个新错误 -
Module not found: Error: Cannot resolve module 'lodash/collection/sortBy'
如果您正在通过this tutorial 工作并遇到此错误,则很可能是由index.js 中的路径不正确引起的,特别是lodash/collections 目录似乎不再存在的事实。我设法通过简单地将路径更改为lodash/sortBy 来解决第二个错误。
注意
请务必先检查lodash 是否安装在node_modules 中,并且在更改之前手动手动检查路径是否正确。
【问题讨论】:
标签: javascript webpack babeljs