任务描述
新工作的第一个任务,vue-cli3 + vue3 项目在firefox(47)浏览器提示异常,且无法正常加载页面,提示异常SyntaxError: missing = in const declara。
“有时间吗?来看一下这个问题。”
SyntaxError: missing = in const declaration
问题分析思路
本地启动项目,F12打开调试工具发现具体文件的异常。
["./node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js"]()
找到对应文件搜索 const 关键字,发现有两种情况
const constName = ***for (const key in obj)
- 修改该源文件中的所有 const 改为 let 发现异常文件发生了变化。
["./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js"]()
- 只修改 for ... in 中的 const 也同样奏效,从而定位到是 for in 语法中的 const 问题。
- const 是 ES6 的语法,在 firefox 的控制台直接输入下面代码也会提示异常。
const obj = {a: 1}
for(const key='' in obj){
console.log(key)
}
- 定位到是 firefox 对于
for(const key='' in obj)语法的不支持,需要进行转译。 - 将源码改回初始状态,且聚焦
vue.config.js配置文件,查看 vue-cli 文档 Babel 配置
同时查阅指南中的 Polyfill 章节。
如果该依赖基于一个目标环境不支持的 ES 版本撰写: 将其添加到
vue.config.js中的transpileDependencies选项。这会为该依赖同时开启语法转换和根据使用情况检测 polyfill。
💡 默认情况下 babel-loader 会忽略所有 node_modules 中的文件。如果你想要通过 Babel 显式转译一个依赖,可以在这个选项中列出来。
- 根据 firefox 浏览器中的异常文件,配置 node_modules 中抛出异常的文件进行 Babel 显式转译。
transpileDependencies: [
/[/\\]node_modules[/\\][@\\]vue[/\\]/,
/[/\\]node_modules[/\\]vue-router[/\\]/,
/[/\\]node_modules[/\\]element-plus[/\\]/
]
- 重启项目。发现奏效!
npm run build打包后本地测试奏效!
补充:打包后文件本地运行
- 在
dist统计目录下创建serve.js文件
/**
* npm install express http
*/
// eslint-disable-next-line @typescript-eslint/no-var-requires
const express = require('express');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const http = require('http');
const app = express();
app.use(express.static('./dist'));
app.get('/', function(req, res) {
res.sendFile('./dist/index.html');
});
const port = 5001;
var httpsServer = app.listen(port, function () {
const host = httpsServer.address().address;
const port = httpsServer.address().port;
console.log('app listening at http://%s:%s', host, port);
});
- 启动 node 服务
node serve.js
- 预览打包后的页面 localhost:5001 (1中设置的端口号为5001)
补充:devServer.proxy 正则匹配
devServer: {
port: 8080,
proxy: {
'/*^(?!/page).*$': {
target: '接口远程地址',
secure: false, // 使用的是http协议则设置为false,https协议则设置为true
changeOrigin: true, // 是否支持跨域
pathRewrite: {
'': '/'
}
}
}
},
💡 匹配所有不以
/page开头的路径,其中^(?!/page)表示排除以/page开头的。
补充:创建 vue3 + ts 项目
- 全局安装 vue-cli vue-cli 4.5.3 及以上版本
npm install -g @vue/cli
// 或者
yarn global add @vue/cli
🔗 参考链接
- 创建项目
vue create vue3_ts_project
Manually select features
...
cd vue3_ts_project
npm run serve