Webpack项目捆绑并运行,但未呈现任何内容

pinkon5k  于 2023-01-26  发布在  Webpack
关注(0)|答案(1)|浏览(125)

我已经在React Typescript中编写了一个组件(如果相关的话,也可以使用Next),我正在尝试将其与Webpack一起使用。当我运行代码时,没有控制台错误,它会构建,但根本不会呈现任何内容。我将主组件放在/pages/index. tsx中。我做错了什么?我如何才能让组件显示出来?
webpack.config.js

const path = require('path')

module.exports = {
 entry: './pages/index.tsx',
 module: {
   rules: [
     {
       test: /\.(ts|tsx|js|jsx)$/,
       exclude: /node_modules/,
       use: ['babel-loader']
     },
     {
       test: /\.css$/,
       use: ["style-loader", "css-loader"]
     },
     {
       test: /\.(pdf|jpg|png|gif|svg|ico)$/,
       use: [
         {
           loader: 'url-loader'
         },
       ]
     },
     {  
       test: /\.(woff|woff2|eot|ttf|otf)$/,
       loader: "file-loader"
     }
   ]
 },
 resolve: {
   extensions: ['*', '.js', '.jsx', '.ts', '.tsx']
 },
 output: {
   path: __dirname + '/dist',
   publicPath: '/',
   filename: 'bundle.js'
 },
 devServer: {
   static: {
     directory: path.join(__dirname, 'dist')
   }
 }
};

package.json

{
  "name": "widget",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "webpack",
    "start": "webpack-dev-server --config ./webpack.config.js --mode development --progress --color --port 3000",
    "lint": "next lint"
  },
  "dependencies": {
    "@next/font": "13.1.1",
    "@types/node": "18.11.18",
    "@types/react": "18.0.26",
    "@types/react-dom": "18.0.10",
    "css-loader": "^6.7.3",
    "eslint": "8.31.0",
    "eslint-config-next": "13.1.1",
    "next": "13.1.1",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "style-loader": "^3.3.1",
    "typescript": "4.9.4",
    "util": "^0.12.5"
  },
  "devDependencies": {
    "@babel/core": "^7.20.12",
    "@babel/plugin-proposal-class-properties": "^7.18.6",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "autoprefixer": "^10.4.13",
    "babel-loader": "^9.1.2",
    "postcss": "^8.4.21",
    "tailwindcss": "^3.2.4",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-dev-server": "^4.11.1"
  }
}

巴伯尔

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "next/babel"
  ]
}
lkaoscv7

lkaoscv71#

1-要获取正确的路径,请连接目录

output: {
    path: path.join(__dirname, "dist"),
    filename: "bundle.js",
    publicPath: "/",
  },

2-你需要添加打印脚本预置到.babelrc

"presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],

3-由于您没有使用HtmlWebpackPlugin,因此需要确保index.html位于dist文件夹中,并且在index.html中,最好将此行放在body元素的底部

<script src="bundle.js"></script>

在单页应用程序中,index.html首先发送到浏览器,然后浏览器读取script元素,因为您设置了publicPath: '/',,它将转到dist文件夹的同一目录以获取javascript包。
如果要使用/html-webpack-plugin/ visit here

相关问题