为什么Vue项目在index.html引入webpack打包文件时报Unexpected token错误?
问题解决
1. 修复Uncaught SyntaxError: Unexpected token '<'报错
原因
当前配置存在两个冲突点:
- index.html 中使用了
htmlWebpackPlugin的模板占位符(如<%= htmlWebpackPlugin.options.title %>),但webpack配置中没有引入和配置该插件 - 手动在index.html中添加了
<script src="../dist/main.js"></script>,开发模式下webpack-dev-server的打包产物存在于内存中,本地相对路径无法访问到该文件,服务器返回404的HTML页面,浏览器将HTML当做JS解析时就会触发首字符为<的语法错误
修复步骤
- 安装依赖:
npm install html-webpack-plugin -D
- 修改webpack.config.js,新增html-webpack-plugin配置:
const path = require('path'); const VueLoaderPlugin = require('vue-loader/lib/plugin') // 新增引入 const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { entry: './src/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist'), // 新增publicPath,避免开发环境资源路径错误 publicPath: '/' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } }, { test: /\.vue$/, loader: 'vue-loader' }, { test: /\.css$/, use: [ 'vue-style-loader', 'css-loader' ] }, // 新增图片资源处理规则,webpack5内置了资源模块无需额外安装loader { test: /\.(png|jpe?g|gif)$/i, type: 'asset/resource' } ] }, plugins: [ new VueLoaderPlugin(), // 新增插件实例 new HtmlWebpackPlugin({ template: './index.html', // 指定你的HTML模板路径 title: '你的项目标题' }) ] };
- 删除index.html中手动添加的
<script src="../dist/main.js"></script>行,插件会自动注入打包后的JS文件。
2. 修复TypeError: __webpack_require__(...).context is not a function报错
原因
require.context是Webpack编译期执行的API,所有参数必须是编译期就能确定的静态字面量,你传入了运行时才会赋值的this.imageDir变量,Webpack编译阶段无法识别该参数,就会抛出该方法不存在的错误。
修复步骤
修改Art.vue中的代码:
- 将
require.context的第一个参数替换为静态字面量 - 导入返回的资源本身就是打包后的正确路径,无需手动拼接路径
修改后的代码如下:
<template> <div> <h1>Art</h1> <ArtImage :key="key" v-for="(img, key) in images" :link="img" /> <div :key="key" v-for="(img, key) in images" > <img :src="img" class="" > </div> </div> </template> <script> import ArtImage from "../components/ArtImage.vue" export default { components: { ArtImage, }, data() { return { images: {} } }, mounted() { // 直接传静态路径字面量,不要用变量 this.importAll(require.context('../assets', true, /\.png$/)) }, methods: { importAll(r) { var imgs = {} r.keys().forEach(key => (imgs[key] = r(key))) this.images = imgs } } } </script>
内容的提问来源于stack exchange,提问作者Robin G
相关产品推荐
相关产品推荐

