【发布时间】:2020-12-15 17:12:10
【问题描述】:
我正在尝试在我的 wepback 项目中包含一个节点模块 (primitive-ellipsoid)。该模块未转译为 es5,因此在浏览器中使用时会引发错误:
Uncaught Error: Module parse failed: /Users/kevzettler/code/crashgiants/node_modules/primitive-ellipsoid/index.js Unexpected token (8:4)
You may need an appropriate loader to handle this file type.
| // Default to an oblate spheroid
| const { latSegments = 32, lngSegments = 64, rx = 2, ry = 1, rz = 1 } = {
| ...options
| };
|
此项目是一个较旧的 create-react-app webpack,已被弹出。
"webpack": "3.5.1",
"webpack-dev-server": "2.8.2",
"webpack-manifest-plugin": "1.2.1",
它正在使用babel 和babel-loader 和worker-loader 我有一个webpack.config.dev.js,其规则如下:
rules: [
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: [
paths.appSrc,
],
exclude: /\.worker.js$/,
loader: require.resolve('babel-loader'),
options: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
//cacheDirectory: true,
},
},
{
test: /\.worker.js$/,
exclude: /node_modules/,
use: [
'worker-loader',
require.resolve('babel-loader'),
]
}
]
我在 package.json 中配置了 babel:
"babel": {
"plugins": [
"babel-plugin-transform-decorators-legacy"
],
"presets": [
[
"env",
{
"targets": "defaults"
}
],
"flow",
"react-app"
]
},
我曾尝试在 webpack.config.json 中弄乱includes 和excludes,但没有成功。如果我需要关注 worker-loader 规则,我会感到困惑,因为它也使用 babel-loader 或者顶级 babel-loader 也被应用。
更新如果我转译整个node_modules,我只想转译特定的node_module/primitive-ellipsoid,还有很多其他问题。我试过了
{
test: /\.(js|jsx)$/,
include: [
'node_modules/primitive-ellipsoid',
paths.appSrc,
],
exclude: /\.worker.js$/,
loader: require.resolve('babel-loader'),
options: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
//cacheDirectory: true,
},
},
但这有同样的错误。
【问题讨论】:
-
worker-loader仅适用于.worker.js文件。您可以尝试从第一条规则中删除include字段。 -
在当前设置下,没有规则匹配
node_modules中的任何内容,因此问题出在。 -
是的,您需要排除过滤器
node_modules,但您的工作人员使用的过滤器如下:exclude: /(clientlib_base)|(node_modules\/(?!(primitive-ellipsoid)/
标签: javascript webpack create-react-app babeljs babel-loader