使用 Webpack 捆绑模块很新,但尝试一下。我有一个非常简单的项目,我试图将其捆绑起来以显示它。运行构建脚本给了我一个神秘的错误:
$ npm run build
> react-extension-from-scratch@1.0.0 build /path/to/react-extension-from-scratch
> webpack --mode production
[webpack-cli] Compilation finished
assets by status 126 KiB [cached] 2 assets
orphan modules 196 bytes [orphan] 1 module
modules by path ./node_modules/ 133 KiB
modules by path ./node_modules/react/ 6.48 KiB
./node_modules/react/index.js 190 bytes [built] [code generated]
./node_modules/react/cjs/react.production.min.js 6.3 KiB [built] [code generated]
modules by path ./node_modules/react-dom/ 119 KiB
./node_modules/react-dom/index.js 1.33 KiB [built] [code generated]
./node_modules/react-dom/cjs/react-dom.production.min.js 118 KiB [built] [code generated]
modules by path ./node_modules/scheduler/ 4.91 KiB
./node_modules/scheduler/index.js 198 bytes [built] [code generated]
./node_modules/scheduler/cjs/scheduler.production.min.js 4.72 KiB [built] [code generated]
./node_modules/object-assign/index.js 2.06 KiB [built] [code generated]
./src/index.tsx + 1 modules 453 bytes [built] [code generated]
1 ERROR in child compilations
webpack 5.11.0 compiled with 1 error in 2831 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! react-extension-from-scratch@1.0.0 build: `webpack --mode production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the react-extension-from-scratch@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /path/to/logfile.log
下面是我的Webpack配置:
import path from 'path';
import webpack from 'webpack';
const CopyPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const config: webpack.Configuration = {
context: __dirname,
devServer: {
contentBase: './src',
historyApiFallback: true,
},
entry: {
app: './src/index.tsx',
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
module: {
rules: [
{
test: /\.html$/,
use: ['html-loader'],
},
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
},
},
},
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src', 'index.html'),
}),
new CopyPlugin({
patterns: [{ from: './src/manifest.json', to: '[name].[ext]' }],
}),
],
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
},
stats: {
errorDetails: true,
},
};
export default config;
奇怪的是,如果我template
从HtmlWebpackPlugin
' 的参数中删除 ,构建工作正常(但显然它不会将index.html
我想要的文件添加到构建目录中)。
对于上下文,这个想法非常简单:在我的 src 目录中,我有一个index.html
文件,其中包含一个带有 id 的 div,我将一些 React 代码注入其中。在构建它时,我想将它捆绑index.html
到构建目录中并让它链接到生成的bundle.js
文件,以便 React 代码立即运行。我知道我可以使用CopyWebpackPlugin
来实现这一点,但必须手动将其包含bundle.js
在其中,这对于这个玩具项目来说很好,但不想对更复杂的项目这样做。
有人有想法吗?