遇到的问题:
根据 webpack v5.4.0 官方教程导入 CSS 文件后,添加了 style-loader 和 css-loader,打包正常,但在浏览器运行时报错 Uncaught SyntaxError: Invalid or unexpected token。
解决方法:
转换文件编码
1.当前项目中安装 webpack-encoding-plugin (不加 --save-dev)
npm install webpack-encoding-plugin
2.webpack.config.js 文件中使用该插件 (注意 两个 loader 的使用顺序)
//webpack.config.js
const path = require('path');const EncodingPlugin = require('webpack-encoding-plugin');module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ], }, ], }, plugins: [new EncodingPlugin({ encoding: 'utf-8' })]};
3.html 文件中设置字符集
<!doctype html><html> <head> <title>Asset Management</title> </head> <body> <script src="bundle.js" charset="utf-8"></script> </body></html>