Trying to load Angular from Rails - "cannot use import statement outside a module"

32 views Asked by At

I'm on a team that maintains a rather creaky old web application. The backend is in Rails; the frontend is based on Rails but in practice is mostly AngularJS.

The project I'm trying to do now is to put modern Angular into the app, with the goal of replacing AngularJS. I would rather write a new Angular frontend app from the ground up, especially as I'm not much of a Rails dev, but I don't think that's on the table right now.

Anyway, each section of the app loads a bunch of JS from a manifest file. Looks vaguely like this:

index.js

//=require jquery
//=require bootstrap
//=require bobs-custom-module
//=require alices-page

As far as I can tell, the Rails asset pipeline is set up to load all of these things whenever you go to the section of the website associated with that particular manifest file. I think Sprockets is doing that? I'd love to tell you more, but again I'm not much of a Rails dev, so you'll have to be specific with your questions.

Anyway, I figured this is where I should try loading Angular, since I can't put it in its own app. I added a line like //=require foo to the manifest file, so now foo.js runs when you load the website. So far, so good. But then I try to write anything like this:

foo.js

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

...and I just get the "Cannot use import statement outside a module" console error. I've tried using require instead of import, and it does run without errors, but it also doesn't load the modules correctly. I've looked for ways to designate foo.js as a module, but they all seem to ask me to modify the <script> tag or package.json or something else that I'm not actually using. Any ideas?

0

There are 0 answers