Uncaught ReferenceError: exports is not defined
发布于 7 年前 作者 wanghongrui 17910 次浏览 来自 问答

使用的是Vue-cli创建的项目,我写了一个js文件,里面有一些会用到的函数。但这里突然就不能用了,找不出什么毛病啊。

import ol from 'openlayers'

const isLayerExist = (id) => {
  let isExist = false
  window.map.getLayers().forEach(function (layer) {
    if (layer.get('id') === id) {
      isExist = true
    }
  })
  return isExist
}

const toggleLayerVisible = (id, show) => {
  window.map.getLayers().forEach(function (layer) {
    if (layer.get('id') === id) {
      layer.setVisible(show)
    }
  })
}

const generateLayer = ({type, url, id}) => {
  switch (type) {
    case 'ImageWMS':
      createImageWMS({url, id})
      break
    default:
      break
  }
}

const createImageWMS = (url, id, opacity = 0.9) => {
  let tiled = new ol.layer.Image({
    opacity: opacity,
    source: new ol.source.ImageWMS({
      url: url,
      wrapX: false
    }),
    visible: true,
    id: id
  })
  window.map.addLayer(tiled)
}

exports.isLayerExist = isLayerExist
exports.toggleLayerVisible = toggleLayerVisible
exports.generateLayer = generateLayer

在组件里面是这样引用的 import maputils from '../utils/maputils'

vue界面就出不来了,引用其他文件是可以的,到这儿就行了,程序界面直接无法访问。命令行里面也没有报错,而浏览器里面说是

Uncaught ReferenceError: exports is not defined

截图06.png

6 回复

解决了。 新版vue-cli生成的.babelrc文件中是这个样子的:

{
  "presets": [
    ["es2015", { "modules": false }],
    "stage-2"
  ],
  "plugins": ["transform-runtime"],
  "comments": false,
  "env": {
    "test": {
      "plugins": [ "istanbul" ]
    }
  }
}

我又改回原来的那个样子,也就是下面这几行代码,这样就不再报错了。至于什么原因导致的,我还真不清楚。

{
  "presets": [
    ["es2015", { "modules": false }],
    "stage-2"
  ],
  "plugins": ["transform-runtime"],
  "comments": false,
  "env": {
    "test": {
      "plugins": [ "istanbul" ]
    }
  }
}

楼上的两段配置,我仔细看半天,上下两段配置是一样的,是不是作者贴错代码了。 因为我是看到作者对.babelrc文件的配置解释,才解决同样的问题。 原因:.babelrc配置中的{ “modules”: false }影响了模块编译。解决:我是直接移除了脚手架对modules的配置。 不知道vue-cli(新)为什么默认的配置是{ “modules”: false },这个确实有待考究。

好诡异的代码… 上半段是 ESM 的 import,下半段又来个 CJM 的 exports,闹哪呀

对于import,export
require,exports的使用方法要保持一致…

建议观察webpack打包的文件,在ESM和CJM使用不一致的时候

function(module,_webpack_require_,....){
   your code
}

在使用一致,并且被外部调用的时候

function(module,exports,_webpack_require_,....){
   your code
}

看到了代码的差别了吧,这就是为什么exports undefine的原因.

为什么会有这种差别?

据说,经过谷歌百度调查,是[transform-runtime]它引起的.

有空翻一下它的源代码看看…

@atian25 @cctv1005s 我对这些概念不太了解。 刚刚查了下资料,import,export是webpack、ES6支持的语法;require、exports是Node支持的语法。 谢谢指出,以后我可得长点心了

回到顶部