webpack打包json文件报错Unexpectedtoken,expected“;“

一、问题

webpack打包json文件报错Unexpected token, expected “;”

错误详情:
ERROR in ./src/testData/movieWeekly.json
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: F:\reactLearning\react-movie\src\testData\movieWeekly.json: Unexpected token, expected “;” (2:14)
{
“subjects”: [{
^
“subject”: {
“rating”: {
“max”: 10,
at Object._raise (F:\reactLearning\react-movie\[email protected]\parser\lib\index.js:799:17)
at Object.raiseWithData (F:\reactLearning\react-movie\[email protected]\parser\lib\index.js:792:17)
at Object.raise (F:\reactLearning\react-movie\[email protected]\parser\lib\index.js:786:17)
at Object.unexpected (F:\reactLearning\react-movie\node_modules*@babel\parser\lib\index.js**:9089:16)
at Object.semicolon (F:\reactLearning\react-movie\node_modules*
@babel\parser\lib\index.js**:9071:40)
at Object.parseExpressionStatement (F:\reactLearning\react-movie\node_modules*@babel\parser\lib\index.js**:12117:10)
at Object.parseStatementContent (F:\reactLearning\react-movie\node_modules*
@babel\parser\lib\index.js**:11713:19)
at Object.parseStatement (F:\reactLearning\react-movie\node_modules*@babel\parser\lib\index.js**:11577:17)
at Object.parseBlockOrModuleBlockBody (F:\reactLearning\react-movie\node_modules*
@babel\parser\lib\index.js**:12159:25)
at Object.parseBlockBody (F:\reactLearning\react-movie\node_modules**@babel\parser\lib\index.js**:12145:10)
@ ./src/components/MovieList.jsx 75:17-56
@ ./src/components/MovieContainer.jsx
@ ./src/components/App.jsx
Child HtmlWebpackCompiler:
1 asset
Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
[./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 528 bytes {HtmlWebpackPlugin_0} [built]
i 「wdm」: Failed to compile.

二、解决方法

  1. 第一反应:检查json文件的数据格式是否正确

  2. 检查后发现格式完全正确,但是依然报错。
    仔细查看报错信息,发现每条错误信息都与 @babel\parser\lib\index.js文件有关——即babel插件在解析json文件时出错
    但这是不合情理的,因为webpack本身就能够解析 json文件,所以json文件无需使用babel插件来解析

  3. 问题的根源webpack.config.js中关于babel插件的配置有误,导致 json文件被babel插件处理,但是babel插件并不能处理json文件。
    所以修改配置使babel插件不解析json文件即可

  4. 错误配置——正则表达式可以匹配 json
    module: {
    rules: [
    { test: /.js|.jsx$/, use: ‘babel-loader’, exclude: /node_modules/ },
    ]
    }

  5. 正确配置——只匹配以.js和.jsx结尾的文件
    module: {
    rules: [
    { test: /(.js|.jsx)$/, use: ‘babel-loader’, exclude: /node_modules/ },
    ]
    }

  6. 正则表达式 /.js|.jsxKaTeX parse error: Can’t use function ‘\.’ in math mode at position 6: /和 /(\̲.̲js|.jsx)是不同的
    webpack打包json文件报错Unexpectedtoken,expected“;“
    乍一看,觉得没有错,两个都是匹配 以.js和.jsx文件结尾的文件。
    然而事实证明/.js|.jsxKaTeX parse error: Can’t use function ‘\.’ in math mode at position 34: …时,该正则表达式被分为两部分 \̲.̲js:匹配所有含有.js的文件…匹配以.jsx结尾的文件

表达式 /(.js|.jsx)KaTeX parse error: Can’t use function ‘\.’ in math mode at position 7: / 和 /\̲.̲js|.jsx$才表示只匹配以.js和.jsx结尾的文件

三、总结

  1. 写正则表达式时要谨慎,尽量保证其准确性,否则可能会造成不可预知的bug

希望对你有帮助!
如有错误,欢迎指正!

本文来源 爱码网,其版权均为 原网址 所有 与本站无关,文章内容系作者个人观点,不代表 本站 对观点赞同或支持。如需转载,请注明文章来源。

© 版权声明

相关文章