导入命名空间为未定义的IIFE包



我有这样的代码:

import * as Phaser from 'phaser';
new Phaser.Game({
width:300,
height:300,
scale: {
mode: Phaser.Scale.FIT,
},
type: Phaser.AUTO,
scene: { create() {} },
});

当我编译并运行它时,我在包中得到这个错误:

Uncaught ReferenceError: Phaser is not defined

rollup.config.js

import typescript from '@rollup/plugin-typescript';
export default {
input: 'src/EntryPoint.ts',
output: {
file: 'dist/EntryPoint.js',
format: 'iife',
},
plugins: [
typescript(),
],
};

index . html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script src="./dist/EntryPoint.js"></script>
</body>
</html>

package.json

{
"name": "rollup-import-issue-mvc",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"build": "rollup -c",
"start": "rollup -c && sirv --dev --max-age 0 --port 3000",
"watch": "rollup -c -w",
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@rollup/plugin-typescript": "^8.3.2",
"phaser": "3.55.2",
"rollup": "^2.72.1",
"sirv-cli": "^2.0.2",
"typescript": "^4.6.4"
}
}

MVC: https://github.com/Klaider/rollupjs-issue-0

这个包是这样的:

(function (Phaser) {
'use strict';
// ...
})(Phaser); // line where I get ReferenceError

结果我也得到了:

(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
phaser (imported by src/EntryPoint.ts)
(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
phaser (guessing 'Phaser')

然而,phaser被指定为NPM依赖。

您可以在警告提供的链接中找到答案:

警告:"将[模块]视为外部依赖">

Rollup默认情况下只解析相对模块id。这意味着像这样的import语句…

import moment from 'moment';

…不会导致moment被包含在你的包中——相反,它将成为运行时所需的外部依赖项。如果这是您想要的,您可以使用external选项抑制此警告,这使您的意图明确:

// rollup.config.js  
export default {  
entry: 'src/index.js',  
dest: 'bundle.js',  
format: 'cjs',  
external: ['moment'] // <-- suppresses the warning  
};

如果你想在bundle中包含这个模块,你需要告诉Rollup如何找到它。在大多数情况下,这是一个使用@rollup/plugin-node-resolve的问题。

一些模块,如eventsutil,被内置到Node.js中。如果你想包含这些(例如,这样你的包就可以在浏览器中运行),你可能需要包含rollup-plugin-polyfill-node。

所以在你的情况下你必须使用@rollup/plugin-node-resolve:

import typescript from '@rollup/plugin-typescript';
import { nodeResolve } from '@rollup/plugin-node-resolve';
export default {
input: 'src/EntryPoint.ts',
output: {
file: 'dist/EntryPoint.js',
format: 'iife',
},
plugins: [
typescript(),
nodeResolve()
],
};

注意:也许你需要使用@rollup/plugin-commonjs,如这里所述

最新更新