rollup使用过程中遇到的各种问题(转载)

小蜗牛 -
rollup使用过程中遇到的各种问题(转载)

原文:https://www.dazhuanlan.com/py...
谁知道我触发了什么神奇的问题 buff,只是想简单地打包个 js,结果碰到这么多问题 (:з」∠)

Missing global variable names
报错信息:

(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
axios (guessing 'axios')
解决方法:

在配置文件增加 global

rollup.config.js

{
external: [

'react',
'react-dom',
'prop-types'

],
output: {

globals: {
  'axios': 'axios'
},
...

},
...
}
参考资料:

https://github.com/rollup/rol...

2.You have passed an unrecognized option
报错信息:

(!) You have passed an unrecognized option
Unknown input option: plugin. Allowed options: acorn, acornInjectPlugins, cache, chunkGroupingSize, context, experimentalCacheExpiry, experimentalOptimizeChunks, experimentalTopLevelAwait, external, inlineDynamicImports, input, manualChunks, moduleContext, onwarn, perf, plugins, preserveModules, preserveSymlinks, shimMissingExports, strictDeprecations, treeshake, watch
解决方法:

我傻了,手残把配置文件中的 plugins 错打成 plugin (:з」∠)

参考资料:

https://github.com/rollup/rol...

3.Babel 7.0.0-beta.56 has dropped support for the ‘helpersNamespace’ utility.
报错信息:

[!] (plugin babel) Error: Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility.If you are using @babel/plugin-external-helpers you will need to use a newer version than the one you currently have installed. If you have your own implementation, you'll want to explore using 'helperGenerator' alongside 'file.availableHelper()'.
解决方法:

方法 1.安装 babel 6.x

npm install --save-dev rollup-plugin-babel@3
安装了之后出现新的问题

[!] Error: Cannot find module 'babel-core'
继续安装 babel-core

npm install --save-dev babel-core
方法 2.安装 babel-upgrade

npm install --save-dev babel-upgrade
安装了之后出现新的问题

[!] (plugin babel) Error: Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility.If you are using @babel/plugin-external-helpers you will need to use a newer version than the one you currently have installed. If you have your own implementation, you'll want to explore using 'helperGenerator' alongside 'file.availableHelper()'.
配置文件 rollup.config.js

plugins: [

//...
babel(
    babelrc({
        addExternalHelpersPlugin: false,
        exclude: /node_modules/,
        runtimeHelpers: false
    })
),
//...

]
有新的报错:

[!] (plugin babel) ReferenceError: Unknown option: .addExternalHelpersPlugin. Check out https://babeljs.io/docs/en/ba... for more information about options.
累了,放弃这个方法 (:з」∠)

参考资料:

https://github.com/rollup/rol...

4.Unexpected token (Note that you need rollup-plugin-json to import JSON files)
报错信息:

[!] Error: Unexpected token (Note that you need rollup-plugin-json to import JSON files)
解决方法:

这个错误看得懂,就安装一下 rollup-plugin-json

npm install --save-dev rollup-plugin-json
添加以下配置到配置文件 rollup.config.js

import json from 'rollup-plugin-json';

export default {
input: 'src/main.js',
output: {

file: 'dist/bundle.js',
format: 'iife'

},

plugins: [

json({
  // 默认情况下将解析所有JSON文件,
  // 但您可以专门包含/排除文件
  include: 'node_modules/**',
  exclude: [ 'node_modules/foo/**', 'node_modules/bar/**' ],

  // 对于 tree-shaking, 属性将声明为
  // 变量, 使用 `var` 或者 `const`
  preferConst: true, // 默认是 false

  // 为生成的默认导出指定缩进 —
  // 默认为 't'
  indent: '  ',

  // 忽略缩进并生成最小的代码
  compact: true, // 默认是 false

  // 为JSON对象的每个属性生成一个命名导出
  namedExports: true // 默认是 true
})

]
};
5.Missing shims for Node.js built-ins
报错信息:

(!) Missing shims for Node.js built-ins
Creating a browser bundle that depends on 'http', 'https', 'url', 'assert', 'stream', 'tty', 'util', 'os' and 'zlib'. You might need to include https://www.npmjs.com/package...
解决方法:

安装 rollup-plugin-node-builtins

npm install --save-dev rollup-plugin-node-builtins
import builtins from 'rollup-plugin-node-builtins';
import globals from 'rollup-plugin-node-globals';
rollup({
entry: 'main.js',
plugins: [

globals(),
builtins()

]
})
6.Cannot find module ‘rollup-plugin-node-globals’
报错信息:

[!] Error: Cannot find module 'rollup-plugin-node-globals'
解决方法:

安装 rollup-plugin-node-globals

npm install --save-dev rollup-plugin-node-globals
7.Plugin node-resolve: preferring built-in module ‘https’……
报错信息:

Plugin node-resolve: preferring built-in module 'https' over local alternative at 'https', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
解决方法:

plugins: [

//...
    resolve({
        preferBuiltins: true,
        mainFields: ['browser']
    }),
//...

]
8.Error: Unexpected character ‘@’ (Note that you need plugins to import files that are not JavaScript)
报错信息:

[!] Error: Unexpected character '@' (Note that you need plugins to import files that are not JavaScript)
node_modulesanimate.cssanimate.css (1:0)
1: @charset "UTF-8";
^
2:
3: /*!
Error: Unexpected character '@' (Note that you need plugins to import files that are not JavaScript)

at error (E:mprojectarcgis3d-d3node_modulesrollupdistrollup.js:9419:30)
at Module.error (E:mprojectarcgis3d-d3node_modulesrollupdistrollup.js:13402:9)
at tryParse (E:mprojectarcgis3d-d3node_modulesrollupdistrollup.js:13315:16)
at Module.setSource (E:mprojectarcgis3d-d3node_modulesrollupdistrollup.js:13629:33)
at Promise.resolve.catch.then.then.then (E:mprojectarcgis3d-d3node_modulesrollupdistrollup.js:16423:20)
at <anonymous>

原因:

不支持 css 文件的打包,需要安装相关的插件

解决方法:

安装 rollup-plugin-css-porter

npm install --save-dev rollup-plugin-css-porter
9.(!) Use of eval is strongly discouraged
报错信息:

(!) Use of eval is strongly discouraged
https://rollupjs.org/guide/en...
packageslocateManagerGeometryZoomCtrl.js
53: ext.xmin += wValue;
54: ext.xmax += wValue;
55: if (typeof eval(ext.expand) == "function") {

                   ^

56: ext = ext.expand(_LocateManagerCtrl.locateManagerCtrl.factor);
57: }
rollup 强烈反对使用 eval,原因:

You probably already know that ‘eval is evil’, at least according to some people. But it’s particularly harmful with Rollup, because of how it works – unlike other module bundlers, which wrap each module in a function, Rollup puts all your code in the same scope. That’s more efficient, but it means that the shared scope is ‘polluted’ whenever you use eval, whereas with a different bundler, modules that didn’t use eval would not be polluted. A minifier can’t mangle variable names in polluted code, because it can’t guarantee that the code to be evaluated doesn’t reference those variable names. Furthermore, it poses a security risk in that a malicious module could access another module’s private variables with eval('SUPER_SEKRIT').
简而言之,它会污染变量而且存在安全隐患。

解决方法:

eval2 = eval
Simply ‘copying’ eval provides you with a function that does exactly the same thing, but which runs in the global scope rather than the local one:
var eval2 = eval;

(function () {
var foo = 42;
eval('console.log("with eval:",foo)'); // logs 'with eval: 42'
eval2('console.log("with eval2:",foo)'); // throws ReferenceError
})();
new Function
Using the Function constructor generates a function from the supplied string. Again, it runs in the global scope. If you need to call the function repeatedly, this is much, much faster than using eval.

(!) this has been rewritten to undefined
报错信息:

(!) this has been rewritten to undefined
https://rollupjs.org/guide/en...
packagesvisualizationesriClusterLayerEsriClusterLayer.js
1:
2: var __extends = this && this.__extends || function () {

                   ^

3: var extendStatics = function (d, b) {
4: extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
...and 5 other occurrences
原因:

为什么会出现这个问题,官方文档是说:

Error: “this is undefined” In a JavaScript module, this is undefined at the top level (i.e., outside functions). Because of that, Rollup will rewrite any this references to undefined so that the resulting behaviour matches what will happen when modules are natively supported. There are occasional valid reasons for this to mean something else. If you’re getting errors in your bundle, you can use options.context and options.moduleContext to change this behaviour.
我本身的情况是因为使用了 es6 中的 class,所以会出现 this,然后被替换成了 undefined。

解决方法:

添加以下配置到配置文件 rollup.config.js

export default {

entry: 'ng2-App/Bootstrapper/Components/main-aot.js',
...
onwarn: function (warning) {
    if (warning.code === 'THIS_IS_UNDEFINED') {
        return;
    }
    console.error(warning.message);
},
plugins: [
    ...
]

};
参考资料:

https://github.com/rollup/rol...

TS2354: This syntax requires an imported helper but module ‘tslib’ cannot be found
报错内容:

TS2354: This syntax requires an imported helper but module 'tslib' cannot be found
解决方法:

下载 tslib

npm install tslib --save-dev

(plugin commonjs) TypeError [ERR_INVALID_ARG_TYPE]: The “path” argument must be of type string
报错内容:

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string
解决方法:

rollup.config.js 配置文件中的input字段输入有误,检查路径是否正确

[!] (plugin babel) SyntaxError
报错内容:

[!] (plugin babel) SyntaxError: E:/mproject/oauth-login-package/node_modules/axios/package.json: Unexpected token, expected ; (2:9)
node_modulesaxiospackage.json (2:9)
SyntaxError: E:/mproject/oauth-login-package/node_modules/axios/package.json: Unexpected token, expected ; (2:9)
1 | {

2 | "_from": "axios@^0.19.0",
|          ^

3 | "_id": "axios@0.19.0",
4 | "_inBundle": false,
5 | "_integrity": "sha1-jgm/89kSLhM/e4EByPvdAO09Krg=",
解决方法:

修改 rollup 配置文件中的 babel 配置

rollup.config.js

     babel({
            exclude: 'node_modules/**',
            runtimeHelpers: true,
        }),
[!] (plugin uglify) Error: Unexpected token: punc «,»
报错内容:

[!] (plugin uglify) Error: Unexpected token: punc «,»
SyntaxError: Unexpected token: punc «,»
解决方法:

这个错误定位后发现与 rollup-plugin-uglify 插件有关,rollup-plugin-uglify 不能压缩 es6 的代码文件。rollup-plugin-uglify 的官方文档是说

Note: uglify-js is able to transpile only es5 syntax. If you want to transpile es6+ syntax use terser instead
顺着这个思路有两种解决方法,一只要把 es6 的代码用 babel 转换成 es5 即可。二使用rollup-plugin-terser插件代替 rollup-plugin-uglify

安装 rollup-plugin-terser

yarn add rollup-plugin-terser --dev
使用 rollup-plugin-terser

import { rollup } from "rollup";
import { terser } from "rollup-plugin-terser";

rollup({
input: "main.js",
plugins: [terser()]
});
15.preferring built-in module ‘http’ over local alternative at ‘http’, pass ‘preferBuiltins: false’ to disable this behavior or ‘preferBuiltins: true’ to disable this warning
报错内容:

(!) Plugin node-resolve: preferring built-in module 'http' over local alternative at 'http', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
(!) Plugin node-resolve: preferring built-in module 'https' over local alternative at 'https', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
(!) Plugin node-resolve: preferring built-in module 'zlib' over local alternative at 'zlib', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
解决方法:

设置 rollup.config.js

plugins: [

...
resolve({
    preferBuiltins: true, //这一句是重点
    mainFields: ['browser']
}),
...

],
或者可以这么做

export default {

...
external: ['http', 'https', 'zlib'],
...

}
16.(!) Circular dependency
报错内容:

(!) Circular dependency: node_modulesrollup-plugin-node-builtinssrces6readable-streamduplex.js -> node_modulesrollup-plugin-node-builtinssrces6readable-streamreadable.js -> node_modulesrollup-plugin-node-builtinssrces6readable-streamduplex.js
解决方法:

参考 https://github.com/rollup/rol...

[!] (plugin babel) TypeError: Cannot read property ‘length’ of undefined
报错信息:

[!] (plugin babel) TypeError: Cannot read property 'length' of undefined
packages/index.js
TypeError: Cannot read property 'length' of undefined

at Object.transform$1 (/Users/dany/PROJECT/arcgis-npm-package/gismap4-pipe-package/node_modules/rollup-plugin-babel/dist/rollup-plugin-babel.cjs.js:148:21)
at Promise.resolve.then (/Users/dany/PROJECT/arcgis-npm-package/gismap4-pipe-package/node_modules/rollup/dist/rollup.js:16621:25)

解决方法: 安装 rollup-plugin-babel@4.0.0 以上版本的

npm install --save-dev rollup-plugin-babel@latest
参考资料:

https://github.com/rollup/rol...

[!] (plugin babel) Error: Babel 7.0.0-beta.56 has dropped support for the ‘helpersNamespace’ utility.
报错信息:

[!] (plugin babel) Error: Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility.If you are using @babel/plugin-external-helpers you will need to use a newer version than the one you currently have installed. If you have your own implementation, you'll want to explore using 'helperGenerator' alongside 'file.availableHelper()

Error: Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility.If you are using @babel/plugin-external-helpers you will need to use a newer version than the one you currently have installed. If you have your own implementation, you'll want to explore using 'helperGenerator' alongside 'file.availableHelper()'.

at File.set (/Users/dany/PROJECT/arcgis-npm-package/gismap4-pipe-package/node_modules/@babel/core/lib/transformation/file/file.js:127:13)
at PluginPass.pre (/Users/dany/PROJECT/arcgis-npm-package/gismap4-pipe-package/node_modules/babel-plugin-external-helpers/lib/index.js:10:12)
at transformFile (/Users/dany/PROJECT/arcgis-npm-package/gismap4-pipe-package/node_modules/@babel/core/lib/transformation/index.js:78:27)
at runSync (/Users/dany/PROJECT/arcgis-npm-package/gismap4-pipe-package/node_modules/@babel/core/lib/transformation/index.js:45:3)
at transformSync (/Users/dany/PROJECT/arcgis-npm-package/gismap4-pipe-package/node_modules/@babel/core/lib/transform.js:43:38)
at Object.transform (/Users/dany/PROJECT/arcgis-npm-package/gismap4-pipe-package/node_modules/@babel/core/lib/transform.js:22:38)
at /Users/dany/PROJECT/arcgis-npm-package/gismap4-pipe-package/node_modules/rollup-plugin-babel/dist/rollup-plugin-babel.cjs.js:57:26
at Object.transform$1 (/Users/dany/PROJECT/arcgis-npm-package/gismap4-pipe-package/node_modules/rollup-plugin-babel/dist/rollup-plugin-babel.cjs.js:141:18)
at Promise.resolve.then (/Users/dany/PROJECT/arcgis-npm-package/gismap4-pipe-package/node_modules/rollup/dist/rollup.js:16621:25)

解决方法: 下载安装@babel/plugin-external-helpers

npm install --save-dev @babel/plugin-external-helpers

特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

javascriptnode.js

扩展阅读

加个好友,技术交流

1628738909466805.jpg