简体   繁体   English

Angular 2 AoT Rollup失败,'require is not defined'

[英]Angular 2 AoT Rollup fails with 'require is not defined'

I have and Angular2 application that I'm compiling to run with AoT. 我有和我正在编译的Angular2应用程序与AoT一起运行。 I've solved the issues I had with the actual compilation and I've also been able to run Rollup from start to end without errors (although there's a lot of warning, which I think are to be expected). 我已经解决了实际编译中遇到的问题,并且我也能够从头到尾运行Rollup而没有错误(尽管有很多警告,我认为这是预期的)。

However, when running the application, the browser always states that require is not defined on my app.bundle.js. 然而,运行应用程序时,浏览器总是说require is not defined在我app.bundle.js。

What am I doing wrong? 我究竟做错了什么?

Here's my functional non-AoT sample code/configs: https://plnkr.co/edit/oCAaeXUKWGyd34YKgho9?p=info 这是我的功能性非AoT示例代码/配置: https ://plnkr.co/edit/oCAaeXUKWGyd34YKgho9?p = info

And here is my functional AoT sample configs that throw the require error: https://plnkr.co/edit/Y1C5HaQS3ddCBrbRaaoM?p=info 这是我的功能性AoT示例配置,它会抛出require错误: https ://plnkr.co/edit/Y1C5HaQS3ddCBrbRaaoM?p = info

Does anyone find any errors here, especially when comparing the non-AoT system.js configs and the AoT rollup configs? 有没有人在这里发现任何错误,特别是在比较非AoT system.js配置和AoT汇总配置时? Why am I hitting this error? 为什么我会遇到这个错误?

I understand that the browser is incapable of working with require but shouldn't rollup attend to that? 我知道浏览器无法使用require但是不应该汇总那个吗?

Best Regards 最好的祝福

So, eventually I was able to solve the issue. 所以,最终我能够解决这个问题。

There was a rogue const _ = require("lodash") in the code. 代码中有一个流氓const _ = require("lodash") Once I removed it, it all went along without issues. 一旦我删除它,它一切都没有问题。

Two things worth mentioning: 值得一提的两件事:

  1. Due to memory limitations on node.js (1.7GB of RAM), the ngc command is run with node --max-old-space-size=8192 ./node_modules/.bin/ngc -p tsconfig-aot.json 由于node.js(1.7GB RAM)的内存限制, ngc命令运行时node --max-old-space-size=8192 ./node_modules/.bin/ngc -p tsconfig-aot.json
  2. Again, for the same reason, rollup is run with node --max-old-space-size=8192 ./node_modules/.bin/rollup -c rollup-config.js 同样,出于同样的原因,使用node --max-old-space-size=8192 ./node_modules/.bin/rollup -c rollup-config.js运行rollup node --max-old-space-size=8192 ./node_modules/.bin/rollup -c rollup-config.js

You might be able to get away with --max-old-memory=4096 , depending on the size of your project and memory on your computer. 您可以使用--max-old-memory=4096 ,具体取决于项目的大小和计算机上的内存。

As for my rollup-config.js, though I'm not sure if everything here is really necessary, here's what worked for me: 至于我的rollup-config.js,虽然我不确定这里的所有内容是否真的有必要,但这对我有用:

import builtins from 'rollup-plugin-node-builtins';
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';

export default {
    entry: 'app/app.aot.js',
    dest: 'www/bundle.js', // output a single application bundle
    sourceMap: false,
    format: 'iife',
    plugins: [
        nodeResolve({
            jsnext: true,
            module: true,
            browser: true
        }),
        commonjs({
            // non-CommonJS modules will be ignored, but you can also
            // specifically include/exclude files
            include: [
                'node_modules/**',
                'node_modules/primeng/**',
                'node_modules/moment/**',
                'node_modules/rxjs/**',
                'node_modules/lodash/**'
            ], // Default: undefined
            exclude: ['node_modules/ws/**'], // Default: undefined

            // search for files other than .js files (must already
            // be transpiled by a previous plugin!)
            extensions: ['.js'], // Default: [ '.js' ]

            // if true then uses of `global` won't be dealt with by this plugin
            ignoreGlobal: false, // Default: false

            namedExports: {
                // left-hand side can be an absolute path, a path
                // relative to the current directory, or the name
                // of a module in node_modules
                'node_modules/primeng/primeng.js': [
                    'PanelModule',
                    'InputSwitchModule',
                    'InputMaskModule',
                    'ProgressBarModule',
                    'DropdownModule',
                    'CalendarModule',
                    'InputTextModule',
                    'DataTableModule',
                    'DataListModule',
                    'ButtonModule',
                    'DialogModule',
                    'AccordionModule',
                    'RadioButtonModule',
                    'ToggleButtonModule',
                    'CheckboxModule',
                    'SplitButtonModule',
                    'ToolbarModule',
                    'SelectButtonModule',
                    'OverlayPanelModule',
                    'TieredMenuModule',
                    'GrowlModule',
                    'ChartModule',
                    'Checkbox',
                    'Dropdown',
                    'Calendar',
                    'DataGridModule',
                    'DataTable',
                    'MultiSelectModule',
                    'TooltipModule',
                    'FileUploadModule',
                    'TabViewModule',
                    'AutoCompleteModule'
                ],
                'node_modules/ng2-uploader/index.js': ['Ng2Uploader']
            },

            // if false then skip sourceMap generation for CommonJS modules
            sourceMap: false, // Default: true
        }),
        builtins(),
        uglify()
    ]
}

rollup still complains about default imports on some packages, which can be probably solved using the named exports (if you really want to) but even with those warnings everything seems to be running. rollup仍抱怨某些软件包上的默认导入,这可能可以使用命名导出来解决(如果你真的想要),但即使有这些警告,一切似乎都在运行。

As for my "final" tsconfig.json: 至于我的“最终”tsconfig.json:

{
    "compilerOptions": {
        "lib": ["es2015", "dom"],
        "target": "es5",
        "module": "es2015",
        "moduleResolution": "node",
        "declaration": false,
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": true,
        "noImplicitAny": false,
        "watch": false,
        "skipLibCheck": true,
        "allowSyntheticDefaultImports": true,
        "suppressImplicitAnyIndexErrors": true,
        "baseUrl": ".",
        "typeRoots": [
            "./node_modules/@types",
            "./node_modules"
        ],
        "types": [
            "node",
            "lodash",
            "jasmine",
            "bluebird",
            "socket.io-client"
        ]
    },
    "compileOnSave": false,
    "buildOnSave": false,
    "files": [
        "app/app.module.ts",
        "app/app.aot.ts"
    ],
    // "exclude": [
    //  "node_modules"

        // ],
        "angularCompilerOptions": {
            "genDir": "compiled",
            "skipMetadataEmit": true
        }
}

Finally, these two links were also helpful in understanding what's going on behind the scenes: 最后,这两个链接也有助于理解幕后发生的事情:

Hope this helps someone. 希望这有助于某人。

My solution for this problem was the following: 我对此问题的解决方案如下:

I tracked, what the system wants to require: the modules fs , events , and timer . 我跟踪了系统想要的内容:模块fs事件计时器 All of them were referenced in the zone.js. 所有这些都在zone.js中被引用。

I've found some zone.js imports hacked into my code in my earlier tries to make in smaller as 5M. 我发现一些zone.js导入入侵我的代码,在我之前的尝试中将其缩小为5M。

After I removed them, the problem disappeared. 删除后,问题就消失了。

For the googlers of the future with a similar problem: 对于具有类似问题的未来的googlers:

The cause of the problem is that your npm module uses require() internally. 问题的原因是你的npm模块在内部使用require() You have to update it, or to recompile it, but this time as ES6 package (which doesn't use require() , it uses import ). 你必须更新它,或重新编译它,但这次作为ES6包(它不使用require() ,它使用import )。 If a require is really deeply hardcoded into it (for example, it is in .js and uses require), then you have to modify its source. 如果require非常硬编码(例如,它在.js中并使用require),那么你必须修改它的源代码。


Additional extension: 附加扩展:

It seems, rollup can't correctly handle non-ordinary imports like import 'Zone.js'; 看来,汇总无法正确处理非普通的进口,例如import 'Zone.js'; and similar! 和类似的! It can handle only import { something } from 'Anything'; 它只能处理import { something } from 'Anything'; -like imports! 像进口!

The root of all problems is that Angular requires zonejs imported on this way, furthermore any typescript decorator require the reflect-metadata package, imported also on this way. 所有问题的根源是Angular需要以这种方式导入zonejs,而且任何typescript装饰器都需要reflect-metadata包,也是以这种方式导入的。

But, it is not really a problem. 但是,这不是一个真正的问题。 Things looked so before, like 事情看起来如此之前,比如

<script src="...zone.js"></script>

Or with an 或者用

import 'zone.js';

, shouldn't be exist in the source (or in the HTML) any more. ,不应该存在于源(或HTML)中。 Instead, you have to compile the sources without them, and then simply concatenate them to the beginning of your source. 相反,你必须在没有它们的情况下编译源代码,然后简单地将它们连接到源代码的开头。 In my case, I use the following Grunt rule: 就我而言,我使用以下Grunt规则:

    concat: {
        dev: {
          src: [ "node_modules/zone.js/dist/zone.js", "node_modules/reflect-metadata/Reflect.js", "target/MyApp-core.js" ],
          dest: "target/MyApp.js"
        }
    },

It is part of the grunt-contrib-concat Grunt package. 它是grunt-contrib-concat Grunt包的一部分。

The resulting target/MyApp.js can be further processed by any other tools (uglify, or the best is google closure compiler). 生成的target/MyApp.js可以通过任何其他工具进一步处理(uglify,或者最好是谷歌闭包编译器)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM