nunjucks: Cannot read property 'MutationObserver' of undefined

nunjucks=2.0.3
node=4.0.0
webpack=1.12.2

Getting an error when importing nunjucks:

Uncaught TypeError: Cannot read property 'MutationObserver' of undefined

looks like this bit of code is triggering it:

var BrowserMutationObserver=global.MutationObserver || global.WebKitMutationObserver;

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 15 (3 by maintainers)

Most upvoted comments

As a workaround, you could use string-replace-webpack-plugin and the following in webpack.config.js. Not ideal but it works:

postLoaders: [{
	test: /\.js$/,
	loader: StringReplacePlugin.replace({
		replacements: [
			// Fix for https://github.com/mozilla/nunjucks/issues/520
			// Because of https://github.com/mozilla/nunjucks/blob/master/browser/nunjucks-slim.js#L1212
			{
				pattern: /global\.MutationObserver/g,
				replacement: function () {
					return "window.MutationObserver";
				}
			},
			{
				pattern: /global\.WebKitMutationObserver/g,
				replacement: function () {
					return "window.WebKitMutationObserver";
				}
			}
		]
	})
}]

I’ve looked into it more closely, and I think you are mistaken. This was fixed in asap 2.0.5 (https://github.com/kriskowal/asap/commit/c5b65d2c0a7dd62c0bd11990b8531f50290072ca), and that fix has been bundled with nunjucks since v3.0.1 (see here). Here it is in the 3.2.0 release:

https://github.com/mozilla/nunjucks/blob/d0ab8d6bf4d7b91fb2c2883f95b172f776d4e531/files/nunjucks-slim.js#L2032-L2033

(In a browser, self in the global scope returns window (MDN Window.self).

There are two possibilities: either you are using Nunjucks 2.x, or you have an old version of asap installed in your own project, and rollup is bundling that.

My motivation for investigating further is that I have been using nunjucks with rollup since 2017, when I took on maintenance of this project (and when 3.0.1 was released), and I’ve never needed a workaround.