简体   繁体   English

使用 Typescript 与 Visual Studio 2017 反应 Js

[英]React Js with Visual studio 2017 with Typescript

I am new in ReactJs so I am try to create new project in visual studio with typescript.by default visual studio provide me template with javascript so I have create new empty project in visual studio.我是 ReactJs 的新手,所以我尝试使用 typescript 在 Visual Studio 中创建新项目。默认情况下,Visual Studio 为我提供带有 javascript 的模板,因此我在 Visual Studio 中创建了新的空项目。

Than I have install below package using Nuget比我使用 Nuget 安装下面的包

npx create-react-app my-app --template typescript
Install-Package Microsoft.AspNetCore.SpaServices.Extensions -Version 2.1.1

Then after I have build my project but get many errors in project.So I have created project with JS template with react and copy below Line in .csproj file and its working fine.but I did not get this why we need to put this line manually in .csproj file.然后在我构建了我的项目但在项目中遇到了很多错误。所以我用 JS 模板创建了项目,并在 .csproj 文件中复制下面的行并且它工作正常。但我不明白为什么我们需要放置这一行在 .csproj 文件中手动。

<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>

So my Question is that Why we need to put this line manually in project and if any better way to implement react js with .net core than please tell me so I can use it with visual studio.所以我的问题是,为什么我们需要在项目中手动放置这条线,以及是否有更好的方法来实现带有 .net 核心的 react js,请告诉我,以便我可以在 Visual Studio 中使用它。

I would personally recommend learning and using Webpack and NPM to manage all frontend stuff and not mess with templates or Nuget packages.我个人建议学习和使用 Webpack 和 NPM 来管理所有前端内容,而不是弄乱模板或 Nuget 包。 These are technologies worth knowing anyways.无论如何,这些都是值得了解的技术。 I know it's very confusing at first, there's quite a bit of legwork involved in getting going and there's no single right way of doing it, but in the end it's best to master the build process yourself.我知道一开始这很令人困惑,开始时涉及很多跑腿工作,并且没有单一的正确方法,但最终最好自己掌握构建过程。

Here is a repo of the steps I'm about to describe: https://github.com/tedchirvasiu/net-core-react-ts-starter这是我将要描述的步骤的回购: https : //github.com/tedchirvasiu/net-core-react-ts-starter

Step 1: Install Node and NPM (if you don't have them already) from https://nodejs.org/en/download/第 1 步:https://nodejs.org/en/download/安装 Node 和 NPM(如果您还没有安装它们)

Step 2: Create a new empty .Net Core web application.第 2 步:创建一个新的.Net Core Web 应用程序。 We're gonna go as bare bones as possible with this.我们将尽可能地做到这一点。

Step 3: Open a command window and change the working directory to your project folder.第 3 步:打开命令窗口并将工作目录更改为您的项目文件夹。 Alternatively, in VS you could right click on your Project and click "Open Folder in File Explorer".或者,在 VS 中,您可以右键单击您的项目,然后单击“在文件资源管理器中打开文件夹”。 Then in the address bar of the windows explorer type "cmd".然后在 Windows 资源管理器的地址栏中键入“cmd”。 This should open a cmd window with the working dir already set.这应该打开一个已设置工作目录的 cmd 窗口。 Now in the command window type the following 2 commands:现在在命令窗口中键入以下 2 个命令:

npm init -y
npm install --save-dev webpack webpack-cli clean-webpack-plugin html-webpack-plugin typescript ts-loader react react-dom @types/react @types/react-dom

The first line will initialize your package.json file.第一行将初始化您的 package.json 文件。 The second line will install webpack, react, typescript, the typings for react and a couple of webpack plugins we're going to use for the build process.第二行将安装 webpack、react、typescript、react 的类型以及我们将用于构建过程的几个 webpack 插件。

Step 4: Since this will be a single page application, we're gonna need a main controller and view to render the initial page.第 4 步:由于这将是一个单页面应用程序,我们将需要一个主控制器和视图来呈现初始页面。 So go to your project, right click, Add -> New Folder and create a folder named "Controllers".因此,转到您的项目,右键单击,添加 -> 新建文件夹并创建一个名为“Controllers”的文件夹。 Right click on the newly created folder, go to Add -> Controller... and create a new empty MVC controller named DefaultController.右键单击新创建的文件夹,转到 Add -> Controller... 并创建一个名为 DefaultController 的新空 MVC 控制器。 This should simply have an Index method returning a View().这应该只是一个返回 View() 的 Index 方法。

Step 5: Create a folder named "Views" and inside it create a folder named "Default" to match your DefaultController.第 5 步:创建一个名为“Views”的文件夹,并在其中创建一个名为“Default”的文件夹以匹配您的 DefaultController。 Basic MVC stuff so far.到目前为止的基本 MVC 内容。 Here comes something different: you're going to create a file named "Index_template.cshtml" with the following content这里有一些不同:您将创建一个名为“Index_template.cshtml”的文件,内容如下

 <!DOCTYPE html> <html> <head> <% for (var css in htmlWebpackPlugin.files.css) { %> <link href="<%= '@Url.Content("~' + htmlWebpackPlugin.files.css[css] + '")' %>" rel="stylesheet"> <% } %> </head> <body> <div id="app"></div> <script> window.baseUrl = "@Url.Content("~/")"; window.resourcesBaseUrl = "@Url.Content("~/dist/")"; </script> <% for (var chunk in htmlWebpackPlugin.files.chunks) { %> <script src="<%= '@Url.Content("~' + htmlWebpackPlugin.files.chunks[chunk].entry + '")' %>"></script> <% } %> </body> </html>

Why _template?为什么是_template? Everytime you change something in your frontend code, Webpack will rebuild your app and create a new bundle (a new big javascript file containing all your code), and this bundle will have a different name everytime (because it contains a hash so you won't have problems with caching).每次您更改前端代码中的某些内容时,Webpack 都会重建您的应用程序并创建一个新包(一个包含所有代码的新大 javascript 文件),并且该包每次都会有一个不同的名称(因为它包含一个哈希值,因此您不会没有缓存问题)。 We don't want to manually update the script reference in our view everytime a new bundle is generated, so we will use Webpack to generate our actual Index.cshtml file.我们不想在每次生成新包时手动更新视图中的脚本引用,因此我们将使用 Webpack 生成实际的 Index.cshtml 文件。 You can see it is not even valid cshtml (you can change the extension to something else if it causes trouble) since it has those <% tags which sort of resemble the old ASPX days.您可以看到它甚至不是有效的 cshtml(如果引起麻烦,您可以将扩展名更改为其他内容),因为它具有那些 <% 标记,类似于旧的 ASPX 时代。 This is called ejs syntax and is used by html-webpack-plugin to know where to insert the bundles.这称为 ejs 语法,由 html-webpack-plugin 使用以了解在哪里插入包。 You can also see we use some razor syntax too to obtain the base URL of the app.您还可以看到我们也使用了一些 razor 语法来获取应用程序的基本 URL。 This is optional for our purpose, but it can come in handy if you host your app as a subsite.这对于我们的目的来说是可选的,但如果您将应用程序托管为子站点,它会派上用场。 You can also obtain other information in this step from the server (like say the application version) without doing other round-trips.您还可以在此步骤中从服务器获取其他信息(例如应用程序版本),而无需进行其他往返。 In really brings the best of all worlds.真正带来了世界上最好的。

Step 6: Update your Startup.cs to use MVC, serve Static Files (to obtain our javascript code) and route all unused paths to our DefaultController.第 6 步:更新您的 Startup.cs 以使用 MVC,提供静态文件(以获取我们的 javascript 代码)并将所有未使用的路径路由到我们的 DefaultController。

    public void ConfigureServices(IServiceCollection services) {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        }

        app.UseStaticFiles();

        app.UseMvc(routes => {
            routes.MapRoute("default", "{controller=Default}/{action=Index}");
            routes.MapRoute("catch-all", "{*url}", new { controller = "Default", action = "Index" });
        });
    }

Step 7: In your project, create a new file named "tsconfig.json" with the following content:第 7 步:在您的项目中,创建一个名为“tsconfig.json”的新文件,内容如下:

 { "compilerOptions": { "baseUrl": "./", "target": "es5", "lib": [ "es2017", "dom" ], "sourceMap": true, "allowJs": true, "noImplicitAny": false, "moduleResolution": "node", "jsx": "react" } }

Make sure the Build Action is set to "None", otherwise VS might get annoying about it and start compiling the ts files for you.确保将 Build Action 设置为“None”,否则 VS 可能会对此感到厌烦并开始为您编译 ts 文件。

Step 8: Now we need to configure webpack.第 8 步:现在我们需要配置 webpack。 Create another file in your project root named "webpack.config.js" with the following code:使用以下代码在项目根目录中创建另一个名为“webpack.config.js”的文件:

 const path = require('path'); const devMode = process.env.NODE_ENV !== 'production'; const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); module.exports = { entry: { app: './src/main.tsx' }, resolve: { extensions: ['.ts', '.tsx', '.js', '.json'] }, devtool: 'source-map', module: { rules: [ { test: /\\.tsx?$/, loader: "ts-loader", include: path.resolve(__dirname, "src"), } ] }, plugins: [ new CleanWebpackPlugin(), //This empties the dist folder new HtmlWebpackPlugin({ chunks: ['app'], inject: false, //We generate the tags manually with lodash templating template: path.resolve(__dirname, 'Views/Default/Index_template.cshtml'), //This is our template filename: path.resolve(__dirname, 'Views/Default/Index.cshtml') //This is our actual Index.cshtml file }) ], output: { filename: devMode ? '[name].bundle.[hash].js' : '[name].bundle.[chunkhash].js', path: path.resolve(__dirname, 'wwwroot/dist'), //This is where our bundles are going to go publicPath: '/dist/' } };

Step 9: We are almost done with the setup.第 9 步:我们几乎完成了设置。 All we have to do now is create a few shortcuts for the commands we are going to use for building.我们现在要做的就是为我们将用于构建的命令创建一些快捷方式。 Go to the package.json file and inside the "scripts" object, use the following:转到 package.json 文件并在“scripts”对象内,使用以下内容:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build-dev": "set NODE_ENV=development&& webpack -d",
    "watch": "set NODE_ENV=development&& webpack --watch -d",
    "build": "set NODE_ENV=production&& webpack -p"
}

Step 10: Okay, this was it for the setup.第 10 步:好的,这就是设置。 All there's left to do is create a new folder in your project named "src".剩下要做的就是在您的项目中创建一个名为“src”的新文件夹。 Here you'll have all your source code for the front-end stuff.在这里,您将拥有前端内容的所有源代码。 Inside src create a main.tsx file.在 src 创建一个 main.tsx 文件。 This will be your entry point.这将是您的切入点。 Paste the following hello-world code in it:将以下 hello-world 代码粘贴到其中:

 import * as React from 'react' import * as ReactDOM from 'react-dom' ReactDOM.render(<div>Hello world!</div>, document.getElementById('app'));

Step 11: Finally let's build and run our app.第 11 步:最后让我们构建并运行我们的应用程序。 In that command window you opened in step 3, type在您在步骤 3 中打开的命令窗口中,键入

npm run watch

This will run the command we specified at step 9 in the package.json file.这将运行我们在第 9 步中在 package.json 文件中指定的命令。 Now webpack will build our app and watch for any changes.现在 webpack 将构建我们的应用程序并观察任何变化。 When it sees that the code in the src was modified, it will rebuild automatically.当它看到 src 中的代码被修改时,它会自动重建。 When you are ready to release, use "npm run build" instead to create an optimized bundle.当您准备发布时,请改用“npm run build”来创建优化包。

Now simply hit play and run your server (F5).现在只需点击播放并运行您的服务器(F5)。 You should see your hello world react app :) Don't forget to check out the repo for reference.您应该会看到您的 hello world react 应用程序 :) 不要忘记查看 repo 以供参考。

I got it working by following these steps:我按照以下步骤让它工作:

https://jonhilton.net/new-aspnet-core-react-project/ https://jonhilton.net/new-aspnet-core-react-project/

... after creating an empty project with the ASP.NET Core 2.2 React + Redux template. ...在使用 ASP.NET Core 2.2 React + Redux 模板创建一个空项目之后。

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

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