Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReactScriptLoadException: Error while loading "~/js/Sample.jsx": SyntaxError: Cannot use import statement outside a module at Sample.jsx:12:1 -> import React from 'react'; #1266

Closed
cataclysm1987 opened this issue Sep 20, 2021 · 5 comments

Comments

@cataclysm1987
Copy link

Thanks for filing a bug! To save time, if you're having trouble using the library, please check off the items you have tried. If you are just asking a question, skip right to the bottom.

Please verify these steps before filing an issue, and check them off as you go

  • [X ] The relevant native JavascriptEngineSwitcher library packages are installed (such as JavaScriptEngineSwitcher.V8.Native.win-x64)
  • [ X] The VC++ 2017 runtime is installed
  • [X ] The value of SetUseReact and SetUseBabel is correct in ReactConfig.cs or Startup.cs
  • [ X] I've looked at the sample projects in this repo to verify that my app is configured correctly

I'm using these library versions:

  • ReactJS.NET: React.Core 5.2.11, React.AspNet 5.2.11
  • JavaScriptEngineSwitcher: JavaScriptEngineSwitcher.V8 3.12.15
  • react and react-dom: (N/A if using bundled react, or version number) N/A
  • webpack: (N/A if using bundled react) N/A
  • node: (N/A if using bundled react) N/A

Runtime environment:

  • OS: (Mac, Windows, Linux flavor. Include 32-bit/64-bit and version): Windows 10
  • .NET Framework or .NET Core Version: .NetCore 3.1.19

Steps to reproduce

Create a .Net Core web app with Azure AD auth. Add Azure tenant information. Add code similar to tutorial section of React JS. Add Sample.jsx file to js folder and reference it in our startup.


I am getting an error when trying to load my index page.

@using React.AspNet

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>


    @Html.React("HelloWorld", new { })

</div>

<script src="@Url.Content(" ~/js/Sample.jsx")" type="module"></script>
@Html.ReactInitJavaScript();

In my startup.cs, ConfigureServices:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
            services.AddRazorPages();
            // Make sure a JS engine is registered, or you will get an error!
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddReact();

            // Make sure a JS engine is registered, or you will get an error!
            services.AddJsEngineSwitcher(options => options.DefaultEngineName = V8JsEngine.EngineName)
              .AddV8();


            services.AddMvc();

        }

And Configure:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                IdentityModelEventSource.ShowPII = true;
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();

            // Initialise ReactJS.NET. Must be before static files.
            app.UseReact(config =>
            {
                // If you want to use server-side rendering of React components,
                // add all the necessary JavaScript files here. This includes
                // your components as well as all of their dependencies.
                // See http://reactjs.net/ for more information. Example:
                config
                  .AddScript("~/js/Sample.jsx")
                  .SetJsonSerializerSettings(new JsonSerializerSettings
                  {
                      StringEscapeHandling = StringEscapeHandling.EscapeHtml,
                      ContractResolver = new CamelCasePropertyNamesContractResolver()
                  });


                // If you use an external build too (for example, Babel, Webpack,
                // Browserify or Gulp), you can improve performance by disabling
                // ReactJS.NET's version of Babel and loading the pre-transpiled
                // scripts. Example:
                //config
                //  .SetLoadBabel(false)
                //  .AddScriptWithoutTransform("~/Scripts/bundle.server.js");
            });

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }

My Sample.jsx contains the import React statements as well as components.

import React from 'react';
import PropTypes from 'prop-types';
import * as Reactstrap from 'reactstrap';

class HelloWorld extends React.Component {
	render() {
		return (<h1>Hello World</h1>);
    }
}

I am getting the error: ReactScriptLoadException: Error while loading "~/js/Sample.jsx": SyntaxError: Cannot use import statement outside a module at Sample.jsx:12:1 -> import React from 'react';

I have tried adding the module to the type when using the reference. I also tried using the Chakra engine and get the same error.

Help is much appreciated.

@dustinsoftware
Copy link
Member

dustinsoftware commented Sep 20, 2021 via email

@cataclysm1987
Copy link
Author

I am using .Net only without Node.js so no.

@Daniel15
Copy link
Member

Modules (import statements) don't work if you use 'vanilla' JS by itself. They only work with a bundler like Webpack.

@cataclysm1987
Copy link
Author

Update - I was able to get this working with a lot of modifications to the Webpack guide but now have a different error as I'm trying to add in my own components.

The webpack guide needs some updates. I was able to piece it together and get it working but it took a few hours. Closing with this comment.

@dustinsoftware
Copy link
Member

dustinsoftware commented Sep 22, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants