인프런 커뮤니티 질문&답변

rail님의 프로필 이미지
rail

작성한 질문수

Slack 클론 코딩[실시간 채팅 with React]

Q&A(CRA를 안 쓰는 이유)

npm run dev - webpack-cli 에러

작성

·

1K

0

npm run dev 했을 때 계속 이런 에러가 납니다!

무슨 오류인지 잘 모르겠습니다..

"scripts": {
    "dev": "cross-env TS_NODE_PROJECT=\"tsconfig-for-webpack-config.json\" webpack serve --env development",
    "build": "cross-env TS_NODE_PROJECT=\"tsconfig-for-webpack-config.json\" NODE_ENV=production webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "@emotion/babel-plugin": "^11.3.0",
    "@emotion/react": "^11.4.1",
    "@emotion/styled": "^11.3.0",
    "@loadable/component": "^5.15.0",
    "@pmmmwh/react-refresh-webpack-plugin": "^0.4.3",
    "@types/react": "^17.0.19",
    "@types/react-dom": "^17.0.9",
    "cross-env": "^7.0.3",
    "css-loader": "^6.2.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router": "^5.2.0",
    "react-router-dom": "^5.2.0",
    "style-loader": "^3.2.1",
    "ts-node": "^10.2.1",
    "typescript": "^4.3.5",
    "webpack-cli": "^4.8.0"
  },
  "devDependencies": {
    "@babel/core": "^7.15.0",
    "@babel/preset-env": "^7.15.0",
    "@babel/preset-react": "^7.14.5",
    "@babel/preset-typescript": "^7.15.0",
    "@types/loadable__component": "^5.13.4",
    "@types/node": "^16.7.1",
    "@types/react-router": "^5.1.16",
    "@types/react-router-dom": "^5.1.8",
    "@types/webpack": "^5.28.0",
    "@types/webpack-dev-server": "^3.11.1",
    "babel-loader": "^8.2.2",
    "eslint": "^7.32.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^3.4.1",
    "fork-ts-checker-webpack-plugin": "^6.3.2",
    "prettier": "^2.3.2",
    "react-refresh": "^0.10.0",
    "webpack": "^5.51.1",
    "webpack-dev-server": "^4.0.0"
  }

답변 2

0

rail님의 프로필 이미지
rail
질문자

적어주신대로 입력해봤는데 에러가 납니다.. configuration 타입에 문제가 있는건가요?

아래는 터미널에서 npm run dev 했을 때 에러이고,

[webpack-cli] Failed to load 'C:\Users\user\Desktop\coding\sleact\client\webpack.config.ts' config
[webpack-cli] webpack.config.ts:80:5 - error TS2322: Type '{ historyApiFallback: true; port: number; static: { publicPath: string; }; }' is not assignable to type 'Configuration'.
  Object literal may only specify known properties, and 'static' does not exist in type 'Configuration'.

80     static: { publicPath: '/dist/' },
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  node_modules/@types/webpack-dev-server/index.d.ts:352:9
    352         devServer?: WebpackDevServer.Configuration;
                ~~~~~~~~~
    The expected type comes from property 'devServer' which is declared here on type 'Configuration'

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! client@1.0.0 dev: `cross-env TS_NODE_PROJECT="tsconfig-for-webpack-config.json" webpack serve --env development`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the client@1.0.0 dev 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!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2021-08-26T14_46_22_658Z-debug.log

아래는 webpack.config.ts 파일 내용입니다. 

import path from 'path';
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
import webpack from 'webpack';
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
// import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';

const isDevelopment = process.env.NODE_ENV !== 'production';

const config: webpack.Configuration = {
  name: 'sleact',
  mode: isDevelopment ? 'development' : 'production',
  devtool: !isDevelopment ? 'hidden-source-map' : 'eval',
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
    alias: {
      '@hooks': path.resolve(__dirname, 'hooks'),
      '@components': path.resolve(__dirname, 'components'),
      '@layouts': path.resolve(__dirname, 'layouts'),
      '@pages': path.resolve(__dirname, 'pages'),
      '@utils': path.resolve(__dirname, 'utils'),
      '@typings': path.resolve(__dirname, 'typings'),
    },
  },
  entry: {
    app: './client',
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'babel-loader',
        options: {
          presets: [
            [
              '@babel/preset-env',
              {
                targets: { browsers: ['last 2 chrome versions'] },
                debug: isDevelopment,
              },
            ],
            '@babel/preset-react',
            '@babel/preset-typescript',
          ],
          env: {
            development: {
              plugins: [['@emotion', { sourceMap: true }], require.resolve('react-refresh/babel')],
            },
            production: {
              plugins: ['@emotion'],
            },
          },
        },
        exclude: path.join(__dirname, 'node_modules'),
      },
      {
        test: /\.css?$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
  plugins: [
    // ts와 webpack 동시에 돌아가게 해주는 플러그인
    new ForkTsCheckerWebpackPlugin({
      async: false,
      // eslint: {
      //   files: "./src/**/*",
      // },
    }),
    new webpack.EnvironmentPlugin({ NODE_ENV: isDevelopment ? 'development' : 'production' }),
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    publicPath: '/dist/',
  },
  devServer: {
    historyApiFallback: true, // react router
    port: 3090,
    // publicPath: '/dist/',
    static: { publicPath: '/dist/' },
    // proxy: {
    //   '/api/': {
    //     target: 'http://localhost:3095',
    //     changeOrigin: true,
    //   },
    // },
  },
};

if (isDevelopment && config.plugins) {
  config.plugins.push(new webpack.HotModuleReplacementPlugin());
  config.plugins.push(new ReactRefreshWebpackPlugin());
  // config.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'server', openAnalyzer: true }));
}
if (!isDevelopment && config.plugins) {
  // config.plugins.push(new webpack.LoaderOptionsPlugin({ minimize: true }));
  // config.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'static' }));
}

export default config;

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

npm i @types/webpack-dev-server@4 하세요.

0

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

devServer 안에 바로 publicPath를 적지 말고 static 객체를 만들고 그 안에 publicPath 해야합니다.

devServer: {

  static: { publicPath: ... },

  다른거

}

rail님의 프로필 이미지
rail

작성한 질문수

질문하기