J
J
Jirafek2022-02-21 14:15:12
typescript
Jirafek, 2022-02-21 14:15:12

Error You need to install 'webpack-dev-server' for running 'webpack serve'. SyntaxError: Unexpected token {?

I have the following error You need to install 'webpack-dev-server' for running 'webpack serve'. SyntaxError: Unexpected token { when I want to do npm start . Here is the complete error 621373afede54940227273.png: webpack config:

const fs = require("fs");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const RemoveEmptyScriptsPlugin = require("webpack-remove-empty-scripts");

const htmlFile = /^([-_\d\w]+).html$/i;
const srcPath = path.resolve(__dirname, "src");

const devServer = (isDev) => !isDev ? {} : {
  devServer: {
    open: true,
    port: "auto",
    static: {
      directory: srcPath,
      watch: true,
    },
  },
};

const getRelative = (absolutePath) => path.relative(srcPath, absolutePath);
const makePath = (relativePath) => "./" + relativePath.replace(/\\+/g, "/");

const getPages = (dir, n) => {
  const dirContent = fs.readdirSync(dir);
  const pages = dirContent
    .filter(f => htmlFile.test(f))
    .reduce((res, f, i) => {
      const name = path.basename(f, path.extname(f));
      res.push({
        name: `p${n += i}`,
        dir: getRelative(dir),
        html: makePath(getRelative(path.join(dir, f))),
        script: dirContent.find(f => new RegExp(`^${name}\.[tj]s$`, "i").test(f)),
        style: dirContent.find(f => new RegExp(`^${name}\.s(c|a)ss$`, "i").test(f)),
      });
      return res;
    }, [])
    .concat(dirContent
      .filter(f => fs.lstatSync(path.resolve(dir, f)).isDirectory())
      .reduce((res, f) => [...res, ...getPages(path.resolve(dir, f), n + 1)], [])
    );

  return pages;
};

const getEntryPoints = (pages) => pages.reduce((entry, {name, dir, script, style}) => Object.assign(entry,
  script ? { [name]: makePath(path.join(dir, script)) } : {},
  style ? { [`${name}-styles`]: makePath(path.join(dir, style)) } : {},
), {});

const getHtmlPlugins = (pages) => pages.map(({html, name, script, style}) => new HtmlWebpackPlugin({
  template: html,
  filename: html,
  chunks: [ script ? name : null, style ? `${name}-styles` : null ].filter(c => !!c),
}));

module.exports = ({ development }) => {
  const pages = getPages(srcPath, 1);
  return {
    mode: development ? "development" : "production",
    devtool: development ? "inline-source-map" : false,
    entry: getEntryPoints(pages),
    context: srcPath,
    output: {
      filename: "js/[name].[contenthash].js",
      path: path.resolve(__dirname, "dist"),
      assetModuleFilename: "[file]",
    },
    target: ["web", "es6"],
    module: {
      rules: [
        {
          test: /\.ts?$/,
          use: "ts-loader",
          exclude: /node_modules/,
        },
        {
          test: /\.(?:ico|gif|png|jpg|jpeg|svg|webp)$/i,
          type: "asset/resource",
        },
        {
          test: /\.(?:mp3|wav|ogg|mp4)$/i,
          type: "asset/resource",
        },
        {
          test: /\.(woff(2)?|eot|ttf|otf)$/i,
          type: "asset/resource",
        },
        {
          test: /\.css$/i,
          use: [{loader: MiniCssExtractPlugin.loader, options: { publicPath: "../" }}, "css-loader"],
        },
        {
          test: /\.s[ac]ss$/i,
          use: [{loader: MiniCssExtractPlugin.loader, options: { publicPath: "../" }}, "css-loader", "sass-loader"]
        }
      ],
    },
    plugins: [
      new MiniCssExtractPlugin({ filename: "css/[name].[contenthash].css" }),
      ...getHtmlPlugins(pages),
      new CopyPlugin({
        patterns: [
          {
            from: "**/*",
            context: srcPath,
            globOptions: {
              ignore: [
                "**/*.js",
                "**/*.ts",
                "**/*.scss",
                "**/*.sass",
                "**/*.html",
              ],
            },
            noErrorOnMissing: true,
            force: true,
          }
        ],
      }),
      new CleanWebpackPlugin(),
      new RemoveEmptyScriptsPlugin(),
    ],
    resolve: {
      extensions: [".js", ".ts"],
    },
    ...devServer(development)
  };
}


package.json:
{
  "version": "0.1.0",
  "description": "My new js application",
  "private": true,
  "name": "my-app",
  "scripts": {
    "start": "webpack serve --env development",
    "build": "webpack"
  },
  "devDependencies": {
    "@types/fabric": "^4.5.6",
    "@typescript-eslint/eslint-plugin": "^5.9.1",
    "@typescript-eslint/parser": "^5.9.1",
    "clean-webpack-plugin": "^4.0.0",
    "copy-webpack-plugin": "^8.1.1",
    "css-loader": "^5.2.7",
    "eslint": "^8.6.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-airbnb-base": "^15.0.0",
    "eslint-plugin-import": "^2.25.4",
    "eslint-plugin-jsx-a11y": "^6.5.1",
    "eslint-plugin-react": "^7.28.0",
    "eslint-plugin-react-hooks": "^4.3.0",
    "html-webpack-plugin": "^5.3.2",
    "mini-css-extract-plugin": "^1.6.2",
    "sass": "^1.42.1",
    "sass-loader": "^11.1.1",
    "webpack": "^5.58.1",
    "webpack-cli": "^4.9.0",
    "webpack-dev-server": "^4.7.3",
    "webpack-remove-empty-scripts": "^0.7.1"
  },
  "dependencies": {
    "ts-loader": "^9.2.6",
    "typescript": "^4.5.4"
  }
}


jsconfig.json:
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs"
  },
  "exclude": ["node_modules", "dist"],
  "include": ["src/**/*"]
}


tsconfig:
{
  "compilerOptions": {
    "outDir": "./dist/",
    "module": "es6",
    "target": "es6",
    "allowJs": true,
    "moduleResolution": "node",
    "noImplicitAny": true,
    "strict": true
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question