В настоящее время я работаю над проектом, используя. Net Core, React с TypeScript, Ant Design для пользовательского интерфейса и Webpack для объединения элементов интерфейса. Когда я запускаю do tnet run, я могу предварительно просмотреть сайт, и он выглядит правильно. Однако, когда я запускаю do tnet publi sh и затем просматриваю опубликованную версию сайта, большая часть CSS является правильной, но есть заметные проблемы с пробелами на одной странице.
Изображение слева - это правильное изображение, запущенное в режиме отладки, а справа - опубликованная версия.
Я пытался выяснить, была ли это проблема с веб-пакетом, но у меня были эти проблемы, когда я запускал веб-пакет в режиме разработчика во время публикации, как и при запуске, tnet запустить, так что кажется, что это не так. проблема; однако, похоже, что какой-то файл или фрагмент информации не копируются во время публикации, так что это все еще может быть проблемой.
Редактировать: После еще одного расследования выясняется, что мое приложение работает ТОЛЬКО, когда оно использует UseWebpackDevMiddleware. При поиске выясняется, что функциональность устарела, поэтому в идеале я должен от нее избавиться; Однако пока я пытаюсь выяснить, почему он будет работать с горячей перезагрузкой, а не тогда, когда все упаковано.
У меня заканчиваются идеи для тестирования, чтобы решить проблему, поэтому, пожалуйста, дайте мне знать, если у вас есть какие-либо мысли о том, на что я должен обратить внимание, которые могут быть причиной этой проблемы. Ниже мой конфиг веб-пакета и файл csproj. Не стесняйтесь, дайте мне знать, если есть что-то еще, что было бы полезно показать.
webpack
const tsImportPluginFactory = require('ts-import-plugin');
const { CheckerPlugin } = require('awesome-typescript-loader');
const isDevelopment = process.env.NODE_ENV === 'development';
const webpack = require('webpack');
const dotenv = require('dotenv');
const path = require('path');
const currentPath = path.join(__dirname);
const appsettingsType = process.env.APP_SETTINGS_TYPE;
const envPath = currentPath + '/.env.' + appsettingsType;
const fileEnv = dotenv.config({ path: envPath }).parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(fileEnv).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(fileEnv[next]);
return prev;
}, {});
module.exports = {
mode: isDevelopment ? 'development' : 'production',
entry: {
main: path.resolve(__dirname, 'src') +"/index.tsx"
},
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist'),
publicPath: "/dist/",
sourceMapFilename: 'bundle.map'
},
// watch: true,
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json", ".less", ".css"],
alias: {
src: './src/*',
'react-dom': '@hot-loader/react-dom'
}
},
plugins: [
new CheckerPlugin(),
new webpack.DefinePlugin(envKeys)
],
//plugins: [],
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{ test: /\.tsx?$/, exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
babelrc: true,
plugins: ['react-hot-loader/babel'],
},
},
{
loader: 'awesome-typescript-loader',
options: {
getCustomTransformers: () => ({
before: [ tsImportPluginFactory(
{
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}
) ]
}),
},
},
],
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" },
{
test: /\.(less)$/,
use: [{
loader: 'style-loader' // creates style nodes from JS strings
}, {
loader: 'css-loader', // translates CSS into CommonJS
}, {
loader: 'less-loader', // compiles Less to CSS
options:{javascriptEnabled:true}
}]},
// All '.css' files will be handle by 'style-loader' and 'css-loader' modules
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader', // translates CSS into CommonJS
},
]
},
{
test: /\.(png|jpe?g|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
}
]
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
"react": "React",
"react-dom": "ReactDOM"
}
};
csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
<TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
<IsPackable>false</IsPackable>
<SpaRoot>wwwroot\</SpaRoot>
<DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Google.Apis.Auth" Version="1.38.2" />
<PackageReference Include="Google.Apis.Gmail.v1" Version="1.38.2.1543" />
<PackageReference Include="Google.Apis.Oauth2.v2" Version="1.38.2.1532" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.4" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="2.2.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
<PackageReference Include="MimeKit" Version="2.1.4" />
<PackageReference Include="MongoDB.Driver" Version="2.8.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="Serilog" Version="2.8.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
</ItemGroup>
<ItemGroup>
<!-- Don't publish the SPA source files, but do show them in the project files list -->
<Content Remove="$(SpaRoot)**" />
<Content Include="wwwroot\.babelrc" />
<Content Include="wwwroot\index.html" />
<Content Include="wwwroot\webpack.config.js" />
<None Remove="$(SpaRoot)**" />
<None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
<None Remove="wwwroot\src\reducers\**" />
<Content Remove="wwwroot\src\reducers\**" />
<None Include="wwwroot\src\utils\appconst.ts" />
</ItemGroup>
<ItemGroup>
<Compile Remove="wwwroot\src\reducers\**" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Remove="wwwroot\src\reducers\**" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\dist" />
</ItemGroup>
<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
<!-- Ensure Node.js is installed -->
<Exec Command="node --version" ContinueOnError="true">
<Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
</Exec>
<Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
<Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
</Target>
<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
<!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build" IgnoreExitCode="true"/>
<!-- Include the newly-built files in the publish output -->
<ItemGroup>
<DistFiles Include="$(SpaRoot)build\**;$(SpaRoot)dist\**;$(SpaRoot)index.html; $(SpaRoot)build-ssr\**" />
<ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
<RelativePath>%(DistFiles.Identity)</RelativePath>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
</Project>