在 Vue CLI 项目中引入本地 JS 文件并使用全局变量时遇到 "Unexpected token" 错误,通常是由于 ES6 模块语法与普通脚本的冲突导致的。以下是解决方案:
在 public/index.html
中使用传统 <script>
标签引入:
<!-- 放在 body 最后 -->
<script src="/path/to/your/file.js"></script>
module.exports = {
configureWebpack: {
externals: {
// 如果你的JS需要作为外部依赖
'globalVar': 'GlobalVarName'
}
}
}
修改你的本地 JS 文件:
// 原写法(可能导致问题)
var globalVar = {...};
// 改为
const globalVar = {...};
export default globalVar;
// 或
window.globalVar = {...}; // 明确挂载到window
然后在组件中:
import globalVar from '@/assets/js/your-file.js'
确保该 JS 文件被 Babel 处理:
// vue.config.js
module.exports = {
chainWebpack: config => {
config.module
.rule('js')
.include
.add('/path/to/your/js')
}
}
确保 JS 文件是 UTF-8 编码(无 BOM)。
src/assets/js/
目录下如果问题仍然存在,请检查浏览器控制台的具体错误信息和行号,这能帮助更精确地定位问题。