我认为使用 CRA 做你想做的事(我也想做)是不可能的,我相信退出后你最终会遇到的复杂性太高而无法管理。
我的出发点:在单个 MVC 控制器/视图(默认索引页面)中运行 Angular.js 前端的大型 ASP MVC 应用程序。
我的目标:停止增长 Angular.js 应用程序并尽可能使用 React 开发新功能,即当它独立于现有 UI 时;我们称之为新模块。我仍然需要将所有内容保存在同一个 MVC 应用程序中,因为它提供身份验证和授权等功能。
解决方案:自定义(相对于 CRA)webpack 构建工具链,其起点是您提供的 youtube example。感谢this other tutorial,我已经能够添加热重载,经过几个小时的反复试验,我添加了css、图像和字体的加载器。捆绑的结果肯定不如 CRA 的结果最优,但它与旧的 Angular.js 共存,所以我相信它已经足够好了。
这是一些代码。
webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const WebpackNotifierPlugin = require('webpack-notifier');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const webpack = require('webpack');
const PUBLIC_PATH = 'Scripts/react/dist';
module.exports = (env, arg) => {
const isDevelopment = arg.mode === 'development';
const fileLoaderName = file => {
if (isDevelopment)
return '[folder]/[name].[ext]';
return '[folder]/[name].[ext]?[contenthash]';
};
return {
entry: './app.js',
watch: isDevelopment,
devtool: isDevelopment ? 'source-map' : undefined,
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
'babel-loader',
{
loader: 'eslint-loader',
options: {
fix: true
}
}
],
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
name: fileLoaderName,
publicPath: PUBLIC_PATH,
postTransformPublicPath: p => `__webpack_public_path__ + ${p}`
}
}
]
},
{
test: /\.(woff|woff2|ttf|otf|eot)$/i,
use: [
{
loader: 'file-loader',
options: {
name: fileLoaderName,
publicPath: PUBLIC_PATH,
postTransformPublicPath: p => `__webpack_public_path__ + ${p}`
}
}
]
}
],
},
plugins: [
new webpack.ProgressPlugin(),
new WebpackNotifierPlugin(),
new BrowserSyncPlugin(),
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({ filename: "bundle.css" })
],
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
}
};
.babelrc
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-transform-runtime"
]
}
.eslintrc
{
"extends": [
"plugin:react-app/recommended",
"prettier"
],
"plugins": [
"prettier"
],
"rules": {
"prettier/prettier": ["error"],
"quotes": [
"error",
"single",
{ "allowTemplateLiterals": true }
]
}
}
.prettierrc
{
"singleQuote": true
}
package.json
...
"scripts": {
"start": "webpack --mode development",
"build": "webpack --mode production",
...
},
仍然缺少一些有用的东西,我计划在未来添加,例如 css 模块和其他 css 优化,但我认为这不会很困难。