在vue中引入cesium报错
./node_modules/cesium/Source/ThirdParty/zip.js
Module parse failed: Unexpected token (6357:57)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
原因是没有对应的加载器
由于在 ./node_modules/cesium/Source/ThirdParty/zip.js 文件中使用了 import.meta 语法,webpack 默认不支持,在进行项目构建时,会报如下错误,提示信息需要添加 loader;
填加插件
npm install @open-wc/webpack-import-meta-loader --save-dev
yarn add @open-wc/webpack-import-meta-loader --dev
vue.config中添加配置
module: {
rules: [
{
test: /\.js$/,
use: {
loader: '@open-wc/webpack-import-meta-loader',
},
},
]}
完整的vue.config.js为
"use strict";
const path = require("path");
const webpack = require("webpack");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const cesiumSource = "node_modules/cesium/Source";
const cesiumWorkers = "../Build/Cesium/Workers";
function resolve(dir) {
return path.join(__dirname, dir);
}
const name = "vue-cesium-demo"; // page title
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
/**
* You will need to set publicPath if you plan to deploy your site under a sub path,
* for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
* then publicPath should be set to "/bar/".
* In most cases please use '/' !!!
* Detail: https://cli.vuejs.org/config/#publicpath
*/
configureWebpack: {
// provide the app's title in webpack's name field, so that
// it can be accessed in index.html to inject the correct title.
name: name,
resolve: {
alias: {
"@": resolve("src"),
// cesium 1
cesium: path.resolve(__dirname, cesiumSource)
}
},
amd: {
// cesium 2
toUrlUndefined: true
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: '@open-wc/webpack-import-meta-loader',
},
},],
// cesium 3 不加这个配置会报require引入警告
unknownContextCritical: false
},
plugins: [
// cesium 4
new webpack.DefinePlugin({
// Define relative base path in cesium for loading assets
CESIUM_BASE_URL: JSON.stringify("")
}), // 对build生效,拷贝到dist目录下。如:dist/Assets
new CopyWebpackPlugin([
{
from: path.join(cesiumSource, cesiumWorkers),
to: "Workers"
}
]),
new CopyWebpackPlugin([
{
from: path.join(cesiumSource, "Assets"),
to: "Assets"
}
]),
new CopyWebpackPlugin([
{
from: path.join(cesiumSource, "Widgets"),
to: "Widgets"
}
]),
new CopyWebpackPlugin([
{
from: path.join(cesiumSource, "ThirdParty"),
to: "ThirdParty"
}
]),
// new webpack.ProvidePlugin({
// Cesium: ['cesium/Cesium'] // Cesium对象实例可在每个js中使用而无须import
// })
]
}
};
即可正常运行
补充 :
上述配置运行没错,但是打包会报错:
原因是有些包是不能用这种loader方式。
解决: 加上include这行代码
{
test: /.js$/,
include: path.resolve(__dirname, 'node_modules/cesium/Source'), //加上
use: { loader: require.resolve('@open-wc/webpack-import-meta-loader') }
}