ngx-translate / core

The internationalization (i18n) library for Angular
MIT License
4.51k stars 577 forks source link

ng build - Unexpected token import error. #581

Closed chriseugenerodriguez closed 7 years ago

chriseugenerodriguez commented 7 years ago

I'm submitting a ... (check one with "x")

[x ] bug report => check the FAQ and search github for a similar issue or PR before submitting
[ ] support request => check the FAQ and search github for a similar issue before submitting
[ ] feature request
H:\d\node_modules\@ngx-translate\core\index.js:1
(function (exports, require, module, __filename, __dirname) { import { NgModule
} from "@angular/core";
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (H:\d\dist\ngfactory\src\app\app.server.module.ngfacto
ry.ts:18:1)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! d@0.0.0 build: `ts-node src/server.ts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the d@0.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\ChrisR\AppData\Roaming\npm-cache\_logs\2017-06-26T16_41_10
_806Z-debug.log

app.server.ts

import { NgModule } from '@angular/core';

import { ServerModule } from '@angular/platform-server'

import { AppComponent } from './app.component';
import { AppModule } from './app.module';

// TRANSLATE
import { TranslateModule, TranslateLoader, TranslateService } from '@ngx-translate/core';
import { translateLoaderFactory } from './core/services/translate.service';

@NgModule({
    imports: [

        ServerModule,
        AppModule,

        // TRANSLATE
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: translateLoaderFactory
            }
        })        
    ],
    bootstrap: [ AppComponent ]
})

export class AppServerModule {}

server.ts

import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server'
import { enableProdMode } from '@angular/core'
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory'
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

const PORT = 4000;

enableProdMode();

const app = express();

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
  const opts = { document: template, url: options.req.url };

  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src')

app.get('*.*', express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}!`);
});
chriseugenerodriguez commented 7 years ago

https://github.com/angular/universal/issues/748

SergiusSidorov commented 7 years ago

Hi! I have the same issue. I prepared an example for reproduce: git@github.com:SergiusSidorov/cli-universal-demo.git

SergiusSidorov commented 7 years ago

I fixed the issue. The issue was in the build configuration. @ngx-translate module should be transpilled. Can be resolved by specifying @ngx-translate in webpack.config.js. More details in repo: https://github.com/SergiusSidorov/cli-universal-demo

chriseugenerodriguez commented 7 years ago

@SergiusSidorov I got error with build using link per your suggestion.

H:\d\node_modules\@ngx-translate\core\src\translate.pipe.js:1
(function (exports, require, module, __filename, __dirname) { import { Pipe, Injectable, ChangeDetectorRef } from '@angular/core';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (H:\d\dist\ngfactory\src\app\layout\pages\home\home.component.ngfactory.ts:10:1)

I added to whitelist and build script using webpage.

    "prebuild": "ng build --prod --no-sourcemap && ngc && webpack",
    "build": "ts-node src/server.ts",
const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  entry: {
    server: './src/server.ts'
  },
  resolve: {
    extensions: ['.ts', '.js']
  },
  target: 'node',
   externals: [nodeExternals({
     whitelist: [
      /^@angular\/material/,
      /^@ngx-translate\/core/,
      /^@ngx-translate\/http-loader/
     ]
   })],
  node: {
    __dirname: true
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js'
  },
  module: {
    rules: [
      { test: /\.ts$/, loader: 'ts-loader' }
    ]
  }
}
SergiusSidorov commented 7 years ago

I think, the mistake in build script. You are use

"prebuild": "ng build --prod --no-sourcemap && ngc && webpack",
"build": "ts-node src/server.ts"

but should be

"prestart": "ng build --prod && gulp before:ngc && ngc && gulp after:ngc && webpack",
"start": "node dist/server.js"

You should use the compiled version of the server script.

Then execute npm run start

chriseugenerodriguez commented 7 years ago

thanks @SergiusSidorov finally got it running, now i got this error when i go to url address.

H:\d>npm run build

> d@0.0.0 prebuild H:\d
> ng build --prod --no-sourcemap && ngc && webpack

Hash: 8fb2d7e301320195c429
Time: 56974ms
chunk    {0} polyfills.f1fbb5539ef2b7bbd352.bundle.js (polyfills) 160 kB {5} [initial] [rendered]
chunk    {1} main.60aac5f92ce9a8072a06.bundle.js (main) 72.9 kB {4} [initial] [rendered]
chunk    {2} scripts.0aa3d564f58ccf154432.bundle.js (scripts) 127 kB {5} [initial] [rendered]
chunk    {3} styles.0b26c5aa70ec35c51c47.bundle.css (styles) 175 bytes {5} [initial] [rendered]
chunk    {4} vendor.ca225b61e86f922d59fe.bundle.js (vendor) 1.47 MB [initial] [rendered]
chunk    {5} inline.e19e8bf5e70e3ca64a10.bundle.js (inline) 0 bytes [entry] [rendered]
ts-loader: Using typescript@2.3.4 and H:\d\tsconfig.json
Hash: 883725545653950b7cd6
Version: webpack 3.2.0
Time: 34270ms
    Asset    Size  Chunks             Chunk Names
server.js  178 kB       0  [emitted]  server
   [9] ./src/app/layout/pages/testing/compute/compute.component.ts 1.08 kB {0} [built]
  [14] ./dist/ngfactory/src/app/layout/pages/home/home.component.ngfactory.ts 3.38 kB {0} [built]
  [17] ./src/app/layout/pages/home/home-routing.module.ts 1.27 kB {0} [built]
  [18] ./src/app/layout/pages/404/notfound-routing.module.ts 1.34 kB {0} [built]
  [19] ./src/app/layout/pages/testing/testing-routing.module.ts 1.63 kB {0} [built]
  [20] ./src/app/layout/pages/testing/history/history.module.ts 1.32 kB {0} [built]
  [21] ./src/app/layout/pages/testing/compute/compute.module.ts 1.32 kB {0} [built]
  [22] ./src/app/layout/shared/header/navigation/nav.module.ts 1.45 kB {0} [built]
  [23] ./dist/ngfactory/src/app/layout/pages/testing/testing.component.ngfactory.ts 1.61 kB {0} [built]
  [24] ./dist/ngfactory/src/app/layout/pages/testing/compute/compute.component.ngfactory.ts 1.34 kB {0} [built]
  [25] ./dist/ngfactory/src/app/layout/pages/testing/history/history.component.ngfactory.ts 1.34 kB {0} [built]
  [26] ./dist/ngfactory/src/app/layout/pages/404/404.component.ngfactory.ts 1.55 kB {0} [built]
  [43] ./dist/ngfactory/src/app/app.component.ngfactory.ts 2.43 kB {0} [built]
  [44] ./dist/ngfactory/src/app/app.server.module.ngfactory.ts 10.5 kB {0} [built]
  [52] ./src/server.ts 1.23 kB {0} [built]
    + 71 hidden modules

> d@0.0.0 build H:\d
> node dist/server.js

listening on http://localhost:4000!
ERROR { TypeError: Cannot read property 'match' of undefined
    at new AppComponent (H:\d\dist\server.js:1847:27)
    at createClass (H:\d\node_modules\@angular\core\bundles\core.umd.js:10943:26)
    at createDirectiveInstance (H:\d\node_modules\@angular\core\bundles\core.umd.js:10774:37)
    at createViewNodes (H:\d\node_modules\@angular\core\bundles\core.umd.js:12210:49)
    at createRootView (H:\d\node_modules\@angular\core\bundles\core.umd.js:12105:5)
    at Object.createProdRootView [as createRootView] (H:\d\node_modules\@angular\core\bundles\core.umd.js:12790:12)
    at ComponentFactory_.create (H:\d\node_modules\@angular\core\bundles\core.umd.js:9888:46)
    at ComponentFactoryBoundToModule.create (H:\d\node_modules\@angular\core\bundles\core.umd.js:3365:29)
    at ApplicationRef_.bootstrap (H:\d\node_modules\@angular\core\bundles\core.umd.js:4794:57)
    at H:\d\node_modules\@angular\core\bundles\core.umd.js:4577:81
  __zone_symbol__currentTask:
   ZoneTask {
     _zone:
      Zone {
        _properties: [Object],
        _parent: [Object],
        _name: 'angular',
        _zoneDelegate: [Object] },
     runCount: 0,
     _zoneDelegates: null,
     _state: 'notScheduled',
     type: 'microTask',
     source: 'Promise.then',
     data: undefined,
     scheduleFn: undefined,
     cancelFn: null,
     callback: [Function],
     invoke: [Function] } }
Unhandled Promise rejection: Cannot read property 'match' of undefined ; Zone: <root> ; Task: Promise.then ; Value: { TypeError: Cannot read property 'match' of undefined
    at new AppComponent (H:\d\dist\server.js:1847:27)
    at createClass (H:\d\node_modules\@angular\core\bundles\core.umd.js:10943:26)
    at createDirectiveInstance (H:\d\node_modules\@angular\core\bundles\core.umd.js:10774:37)
    at createViewNodes (H:\d\node_modules\@angular\core\bundles\core.umd.js:12210:49)
    at createRootView (H:\d\node_modules\@angular\core\bundles\core.umd.js:12105:5)
    at Object.createProdRootView [as createRootView] (H:\d\node_modules\@angular\core\bundles\core.umd.js:12790:12)
    at ComponentFactory_.create (H:\d\node_modules\@angular\core\bundles\core.umd.js:9888:46)
    at ComponentFactoryBoundToModule.create (H:\d\node_modules\@angular\core\bundles\core.umd.js:3365:29)
    at ApplicationRef_.bootstrap (H:\d\node_modules\@angular\core\bundles\core.umd.js:4794:57)
    at H:\d\node_modules\@angular\core\bundles\core.umd.js:4577:81
  __zone_symbol__currentTask:
   ZoneTask {
     _zone:
      Zone {
        _properties: {},
        _parent: null,
        _name: '<root>',
        _zoneDelegate: [Object] },
     runCount: 0,
     _zoneDelegates: null,
     _state: 'notScheduled',
     type: 'microTask',
     source: 'Promise.then',
     data: undefined,
     scheduleFn: undefined,
     cancelFn: null,
     callback: [Function],
     invoke: [Function] } } TypeError: Cannot read property 'match' of undefined
    at new AppComponent (H:\d\dist\server.js:1847:27)
    at createClass (H:\d\node_modules\@angular\core\bundles\core.umd.js:10943:26)
    at createDirectiveInstance (H:\d\node_modules\@angular\core\bundles\core.umd.js:10774:37)
    at createViewNodes (H:\d\node_modules\@angular\core\bundles\core.umd.js:12210:49)
    at createRootView (H:\d\node_modules\@angular\core\bundles\core.umd.js:12105:5)
    at Object.createProdRootView [as createRootView] (H:\d\node_modules\@angular\core\bundles\core.umd.js:12790:12)
    at ComponentFactory_.create (H:\d\node_modules\@angular\core\bundles\core.umd.js:9888:46)
    at ComponentFactoryBoundToModule.create (H:\d\node_modules\@angular\core\bundles\core.umd.js:3365:29)
    at ApplicationRef_.bootstrap (H:\d\node_modules\@angular\core\bundles\core.umd.js:4794:57)
    at H:\d\node_modules\@angular\core\bundles\core.umd.js:4577:81
{ Error: Uncaught (in promise): TypeError: Cannot read property 'match' of undefined
TypeError: Cannot read property 'match' of undefined
    at new AppComponent (H:\d\dist\server.js:1847:27)
    at createClass (H:\d\node_modules\@angular\core\bundles\core.umd.js:10943:26)
    at createDirectiveInstance (H:\d\node_modules\@angular\core\bundles\core.umd.js:10774:37)
    at createViewNodes (H:\d\node_modules\@angular\core\bundles\core.umd.js:12210:49)
    at createRootView (H:\d\node_modules\@angular\core\bundles\core.umd.js:12105:5)
    at Object.createProdRootView [as createRootView] (H:\d\node_modules\@angular\core\bundles\core.umd.js:12790:12)
    at ComponentFactory_.create (H:\d\node_modules\@angular\core\bundles\core.umd.js:9888:46)
    at ComponentFactoryBoundToModule.create (H:\d\node_modules\@angular\core\bundles\core.umd.js:3365:29)
    at ApplicationRef_.bootstrap (H:\d\node_modules\@angular\core\bundles\core.umd.js:4794:57)
    at H:\d\node_modules\@angular\core\bundles\core.umd.js:4577:81
    at resolvePromise (H:\d\node_modules\zone.js\dist\zone-node.js:770:31)
    at resolvePromise (H:\d\node_modules\zone.js\dist\zone-node.js:741:17)
    at H:\d\node_modules\zone.js\dist\zone-node.js:818:17
    at ZoneDelegate.invokeTask (H:\d\node_modules\zone.js\dist\zone-node.js:424:31)
    at Zone.runTask (H:\d\node_modules\zone.js\dist\zone-node.js:191:47)
    at drainMicroTaskQueue (H:\d\node_modules\zone.js\dist\zone-node.js:584:35)
    at Server.ZoneTask.invoke (H:\d\node_modules\zone.js\dist\zone-node.js:490:25)
    at emitTwo (events.js:106:13)
    at Server.emit (events.js:191:7)
    at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:546:12)
  rejection:
   { TypeError: Cannot read property 'match' of undefined
       at new AppComponent (H:\d\dist\server.js:1847:27)
       at createClass (H:\d\node_modules\@angular\core\bundles\core.umd.js:10943:26)
       at createDirectiveInstance (H:\d\node_modules\@angular\core\bundles\core.umd.js:10774:37)
       at createViewNodes (H:\d\node_modules\@angular\core\bundles\core.umd.js:12210:49)
       at createRootView (H:\d\node_modules\@angular\core\bundles\core.umd.js:12105:5)
       at Object.createProdRootView [as createRootView] (H:\d\node_modules\@angular\core\bundles\core.umd.js:12790:12)
       at ComponentFactory_.create (H:\d\node_modules\@angular\core\bundles\core.umd.js:9888:46)
       at ComponentFactoryBoundToModule.create (H:\d\node_modules\@angular\core\bundles\core.umd.js:3365:29)
       at ApplicationRef_.bootstrap (H:\d\node_modules\@angular\core\bundles\core.umd.js:4794:57)
       at H:\d\node_modules\@angular\core\bundles\core.umd.js:4577:81
     __zone_symbol__currentTask:
      ZoneTask {
        _zone: [Object],
        runCount: 0,
        _zoneDelegates: null,
        _state: 'notScheduled',
        type: 'microTask',
        source: 'Promise.then',
        data: undefined,
        scheduleFn: undefined,
        cancelFn: null,
        callback: [Function],
        invoke: [Function] } },
  promise:
   ZoneAwarePromise {
     __zone_symbol__state: 0,
     __zone_symbol__value:
      { TypeError: Cannot read property 'match' of undefined
          at new AppComponent (H:\d\dist\server.js:1847:27)
          at createClass (H:\d\node_modules\@angular\core\bundles\core.umd.js:10943:26)
          at createDirectiveInstance (H:\d\node_modules\@angular\core\bundles\core.umd.js:10774:37)
          at createViewNodes (H:\d\node_modules\@angular\core\bundles\core.umd.js:12210:49)
          at createRootView (H:\d\node_modules\@angular\core\bundles\core.umd.js:12105:5)
          at Object.createProdRootView [as createRootView] (H:\d\node_modules\@angular\core\bundles\core.umd.js:12790:12)
          at ComponentFactory_.create (H:\d\node_modules\@angular\core\bundles\core.umd.js:9888:46)
          at ComponentFactoryBoundToModule.create (H:\d\node_modules\@angular\core\bundles\core.umd.js:3365:29)
          at ApplicationRef_.bootstrap (H:\d\node_modules\@angular\core\bundles\core.umd.js:4794:57)
          at H:\d\node_modules\@angular\core\bundles\core.umd.js:4577:81 __zone_symbol__currentTask: [Object] } },
  zone:
   Zone {
     _properties: {},
     _parent: null,
     _name: '<root>',
     _zoneDelegate:
      ZoneDelegate {
        _taskCounts: [Object],
        zone: [Circular],
        _parentDelegate: null,
        _forkZS: null,
        _forkDlgt: null,
        _forkCurrZone: null,
        _interceptZS: null,
        _interceptDlgt: null,
        _interceptCurrZone: null,
        _invokeZS: null,
        _invokeDlgt: null,
        _invokeCurrZone: null,
        _handleErrorZS: null,
        _handleErrorDlgt: null,
        _handleErrorCurrZone: null,
        _scheduleTaskZS: null,
        _scheduleTaskDlgt: null,
        _scheduleTaskCurrZone: null,
        _invokeTaskZS: null,
        _invokeTaskDlgt: null,
        _invokeTaskCurrZone: null,
        _cancelTaskZS: null,
        _cancelTaskDlgt: null,
        _cancelTaskCurrZone: null,
        _hasTaskZS: null,
        _hasTaskDlgt: null,
        _hasTaskDlgtOwner: null,
        _hasTaskCurrZone: null } },
  task:
   ZoneTask {
     _zone:
      Zone {
        _properties: {},
        _parent: null,
        _name: '<root>',
        _zoneDelegate: [Object] },
     runCount: 0,
     _zoneDelegates: null,
     _state: 'notScheduled',
     type: 'microTask',
     source: 'Promise.then',
     data: undefined,
     scheduleFn: undefined,
     cancelFn: null,
     callback: [Function],
     invoke: [Function] } }
KlaudiaAnnaM commented 7 years ago

@premiumwd How did you resolve your problem?

arlamaeen commented 7 years ago

@KlaudiaMor how did your application go? do you have fix for this?

@premiumwd I tried yours but I still have the same error everytime I put something inside the TranslateModule.forRoot()

ghost commented 7 years ago

I have the same problem, ejected the webpack config using the CLI and added this:

externals : [ nodeExternals({ whitelist : [ /^@ngx-translate\/core/, /^@ngx-translate\/http-loader/, ] }) ],

then running:

"prestart": "npm run build --aot --env=prod --output-hashing && ngc", "start": "ts-node src/server.ts"

Still get the original error:

(function (exports, require, module, filename, dirname) { import { Pipe, Injectable, ChangeDetectorRef } from '@angular/core'; SyntaxError: Unexpected token import at createScript (vm.js:74:10) at Object.runInThisContext (vm.js:116:10) at Module._compile (module.js:533:28) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) at require (internal/module.js:11:18)

AnthonyNahas commented 7 years ago

I fixed the issue as i move all bundles files to the root of the module! --> e.g:

before: node_modules/@ ngrx/core/bundles/ --> core.umd.js & core.min.umd.js (i have moved these files to -->)

after: node_modules/@ngrx/ or node_modules/@ ngrx/core (depends on ur import) -->--> core.umd.js & core.min.umd.js

the same procedure for all umd.js files ! in my case they should be not nested! They should be in the root of the module or submodule! I hope this helps (as workaround)

AnthonyNahas commented 7 years ago

i forked the repo few days ago and i made some updates! please try my version and give me your feedback. If that works your machine, i will make a pull request.

So the solution is the following:

  1. remove the npm module vianpm un --save @ngx-translate/core
  2. install my forked module via npm i --save git+ssh://git@github.com:AnthonyNahas/core.git or npm i --save https://github.com/AnthonyNahas/core.git

Cheers, no more Unexpected token import error 💃

polcham commented 7 years ago

Hi @AnthonyNahas, thanks for your work. I am just wondering if by any chance you have any idea on the following AoT Error. The problem is different with unexpected token, but you may have any idea on this matter, since you generally solved the unexpected token import. Appreciate the lead, been trying to solve this for days with no progress.

screen shot 2017-09-14 at 9 24 36 am
BlankHrt commented 7 years ago

Hi, I met the same problem when using universal with @ngrx import { BehaviorSubject } from 'rxjs/BehaviorSubject'; ^^^^^^ SyntaxError: Unexpected token import

AnthonyNahas commented 7 years ago

@polcham pls post ur npm build script like or tell me which steps are u running to build the app @BlankHrt u need to compile the js files to es2015 - commonjs e.g. with babel cli

polcham commented 7 years ago

@AnthonyNahas I'm using Ionic 3, and calling ionic cordova build android --prod. I opened an issue on it here: https://github.com/ngx-translate/core/issues/666. Thanks so much!

qubiack commented 7 years ago

@AnthonyNahas I think you wait on our feedback, so for me your solution work perfectly. Thank you! I had another error but it was connected with wrong json import.

qubiack commented 7 years ago

@AnthonyNahas - can you look help us also with localize-router? I think that it's the same problem. Maybe you can give me a tips how I can manage with this problem?

/home/xxx/Projects/private/angular4-cli-seed/node_modules/localize-router/src/localize-router.config.js:1
(function (exports, require, module, __filename, __dirname) { import { Inject, OpaqueToken } from '@angular/core';
AnthonyNahas commented 7 years ago

@qubiack please see my full explanation here

u can do the same procedure for every module that throwing this kind of errors!