reactjs / React.NET

.NET library for JSX compilation and server-side rendering of React components
https://reactjs.net/
MIT License
2.28k stars 940 forks source link

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 closed 2 years ago

cataclysm1987 commented 2 years ago

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

I'm using these library versions:

Runtime environment:

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 commented 2 years ago

Does the webpack guide work?

On Mon, Sep 20, 2021 at 10:46, Eric Conklin @.***> wrote:

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"; }

Welcome

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

<script @.***(" ~/js/Sample.jsx")" type="module"> @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 (

Hello World

); } }

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.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/reactjs/React.NET/issues/1266, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAHGCFTYF7DBPKNBRCTXPW3UC5CLVANCNFSM5EMEAC5Q . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.

cataclysm1987 commented 2 years ago

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

Daniel15 commented 2 years ago

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

cataclysm1987 commented 2 years ago

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 commented 2 years ago

Cool, what did you update?

On Tue, Sep 21, 2021 at 10:05, Eric Conklin @.***> wrote:

Closed #1266 https://github.com/reactjs/React.NET/issues/1266.

— You are receiving this because you commented.

Reply to this email directly, view it on GitHub https://github.com/reactjs/React.NET/issues/1266#event-5335899475, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAHGCFWTOXLGMWOAVJ5YTKLUDCGI7ANCNFSM5EMEAC5Q . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.