首页 > 解决方案 > Webpack:缺少脚本 webpack:dev

问题描述

我有一个使用 webpack 在 Web 项目中嵌入 Aurelia 项目的解决方案。

webpack 版本是 4.41.2 webpack-cli 版本是 3.3.10

webpack 被卸载,然后重新安装。

我收到错误消息:

MSB3073 命令“npm run webpack:dev”以代码 1 退出。

如果我检查来自构建的错误,如下所示:

在此处输入图像描述

说它找不到 webpack:dev。

这是详细的日志:

1 verbose cli   'webpack:dev'
1 verbose cli ]
2 info using npm@6.11.3
3 info using node@v12.12.0
4 verbose stack Error: missing script: webpack:dev
4 verbose stack
4 verbose stack Did you mean one of these?
4 verbose stack     webpack:Debug
4 verbose stack     webpack:watch
4 verbose stack     at run (C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:155:19)
4 verbose stack     at C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:63:5
4 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:116:5
4 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:435:5
4 verbose stack     at checkBinReferences_ (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:391:45)
4 verbose stack     at final (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:433:3)
4 verbose stack     at then (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:161:5)
4 verbose stack     at ReadFileContext.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:350:20)
4 verbose stack     at ReadFileContext.callback (C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:115:16)
4 verbose stack     at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:239:13)
5 verbose cwd C:\Users\simon\Documents\AURELIA\1.0 - JobsLedgerSPA -ASPNET CORE 3.1\JobsLedgerSPA\JobsLedger.API
6 verbose Windows_NT 10.0.18363
7 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "webpack:dev"
8 verbose node v12.12.0
9 verbose npm  v6.11.3
10 error missing script: webpack:dev
10 error
10 error Did you mean one of these?
10 error     webpack:Debug
10 error     webpack:watch
11 verbose exit [ 1, true ]

这是我的 package.json:

{
  "name": "JobsLedger.API",
  "private": true,
  "version": "0.0.1",
  "description": "SPA Scheduling and accounting package",
  "scripts": {
    "lint": "tslint --project tsconfig.json",
    "webpack:Debug": "webpack --mode development",
    "webpack:Release": "webpack --mode production",
    "webpack:watch": "webpack --mode development --watch"
  },
  "keywords": [],
  "author": "Simon O'Farell",
  "license": "ISC",
  "devDependencies": {
    "au-table": "^0.1.14",
    "aurelia-animator-css": "^1.0.4",
    "aurelia-api": "^3.2.1",
    "aurelia-binding": "^2.5.0",
    "aurelia-bootstrap": "^0.1.20",
    "aurelia-bootstrapper": "^2.3.3",
    "aurelia-dialog": "^2.0.0-rc.8",
    "aurelia-event-aggregator": "^1.0.3",
    "aurelia-fetch-client": "^1.8.2",
    "aurelia-fontawesome": "^1.0.0-beta.1",
    "aurelia-http-client": "^1.3.1",
    "aurelia-mask": "^2.0.1",
    "aurelia-pal": "^1.8.2",
    "aurelia-router": "^1.7.1",
    "aurelia-slickgrid": "^2.15.1",
    "aurelia-templating": "^1.10.2",
    "aurelia-validation": "^1.5.0",
    "aurelia-webpack-plugin": "^4.0.0",
    "awesome-typescript-loader": "^5.2.1",
    "bootstrap": "^4.4.1",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^3.2.1",
    "es6-promise": "^4.2.8",
    "fetch": "^1.1.0",
    "file-loader": "^5.0.2",
    "font-awesome": "^4.7.0",
    "html-loader": "^1.0.0-alpha.0",
    "html-webpack-plugin": "^4.0.0-beta.11",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^3.4.1",
    "mini-css-extract-plugin": "^0.8.0",
    "node-sass": "^4.13.0",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "popper.js": "^2.0.0-next.4",
    "postcss-loader": "^3.0.0",
    "sass-loader": "^8.0.0",
    "style-loader": "^1.0.1",
    "tether": "^1.4.6",
    "ts-loader": "^6.2.1",
    "tslint": "^6.0.0-beta1",
    "typescript": "^3.7.3",
    "url-loader": "^3.0.0",
    "velocity-animate": "2.0.5",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.26-1",
    "@fortawesome/free-brands-svg-icons": "^5.12.0-1",
    "@fortawesome/free-regular-svg-icons": "^5.12.0-1",
    "@fortawesome/free-solid-svg-icons": "^5.12.0-1"
  }
}

这是我的 csproj 文件:

<Project Sdk="Microsoft.NET.Sdk.Web">

    <PropertyGroup>
        <TargetFramework>netcoreapp3.0</TargetFramework>
        <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
        <TypeScriptToolsVersion>3.6</TypeScriptToolsVersion>
        <TypeScriptBuildMode>true</TypeScriptBuildMode>
    </PropertyGroup>



    <ItemGroup>
      <Compile Remove="ControllerServices\Catalog\UserServices\UserValidateService.cs" />
      <Compile Remove="Controllers\SampleDataController.cs" />
      <Compile Remove="Controllers\SelectDataController.cs" />
    </ItemGroup>

    <ItemGroup>
      <Content Remove="wwwroot\favicon.ico" />
    </ItemGroup>

    <ItemGroup>
      <None Remove="ClientApp\app\components\clients\clientList\client-detail-view.ts" />
      <None Remove="ClientApp\app\components\clients\clientList\objectkeysValueConverter.ts" />
      <None Remove="ClientApp\app\navmenu\ActiveRoute.ts" />
    </ItemGroup>


    <ItemGroup>
        <PackageReference Include="FluentValidation" Version="8.5.0" />
        <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
        <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="5.5.0" />
        <PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.19" />
    </ItemGroup>


    <ItemGroup>
      <Folder Include="wwwroot\" />
    </ItemGroup>


    <ItemGroup>
      <ProjectReference Include="..\JobsLedger.CATALOG\JobsLedger.CATALOG.csproj" />
      <ProjectReference Include="..\JobsLedger.DATA\JobsLedger.DATA.csproj" />
    </ItemGroup>


    <ItemGroup>
      <TypeScriptCompile Include="ClientApp\app\components\clients\clientList\client-detail-view.ts" />
      <TypeScriptCompile Include="ClientApp\app\navmenu\activeRoute.ts" />
    </ItemGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" />
    </ItemGroup>

    <Target Name="DebugRunWebpack" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('wwwroot\dist') ">
        <!-- Ensure Node.js is installed -->
        <Exec Command="node --version" ContinueOnError="true">
            <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
        </Exec>
        <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />

        <!-- In development, the dist files won't exist on the first run or when cloning to
                 a different machine, so rebuild them if not already present. -->
        <Message Importance="high" Text="Performing first-run Webpack build..." />
        <Exec Command="npm install" />
        <Exec Command="npm ddp" />
        <Exec Command="npm run webpack:dev" />
    </Target>

    <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
        <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
        <Exec Command="npm install" />
        <Exec Command="npm ddp" />
        <Exec Command="npm run webpack:$(Configuration)" />

        <!-- Include the newly-built files in the publish output -->
        <ItemGroup>
            <!-- First, clean up previously generated content that may have been removed. -->
            <ContentWithTargetPath Remove="@(ContentWithTargetPath)" Condition="!Exists('%(Identity)')" />
            <_WebpackFiles Include="wwwroot\dist\**" />
            <ContentWithTargetPath Include="@(_WebpackFiles->'%(FullPath)')" RelativePath="%(_WebpackFiles.Identity)" TargetPath="%(_WebpackFiles.Identity)" CopyToPublishDirectory="Always" />
        </ItemGroup>
    </Target>

</Project>

...这是我的 webpack.config.js 文件:

const path = require("path");
const webpack = require("webpack");
const { AureliaPlugin, ModuleDependenciesPlugin, GlobDependenciesPlugin } = require("aurelia-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");

const bundleOutputDir = "./wwwroot/dist";

module.exports = (env, argv) => {
    if ((!argv || !argv.mode) && process.env.ASPNETCORE_ENVIRONMENT === "Development") {
        argv = { mode: "development" };
    }
    console.log("mode =", argv.mode);
    const isDevBuild = argv.mode !== "production";
    const cssLoaders = ["css-loader", "postcss-loader"];
    const scssLoaders = [...cssLoaders, "sass-loader"];

    return [{
        target: "web",
        mode: isDevBuild ? "development" : "production",
        entry: { "app": ["es6-promise/auto", "aurelia-bootstrapper"] },
        resolve: {
            extensions: [".ts", ".js"],
            modules: ["ClientApp", "node_modules"]
        },
        output: {
            path: path.resolve(bundleOutputDir),
            // Asp.Net JavaScriptServices does not tolerate "/" in public path, see https://github.com/aspnet/JavaScriptServices/issues/1495
            publicPath: "dist/",
            filename: "[name].[hash].js",
            chunkFilename: "[name].[chunkhash].js",
            pathinfo: false
        },
        module: {
            rules: [
                { test: /\.(woff|woff2|png|eot|ttf|svg)(\?|$)/, use: { loader: "url-loader", options: { limit: 1, publicPath: "./" } } },
                { test: /\.ts$/i, include: [/ClientApp/], loader: "ts-loader" },
                { test: /\.html$/i, use: "html-loader" },
                { test: /\.css$/i, /*include: [/node_modules/],*/ issuer: /\.html$/i, use: cssLoaders },
                { test: /\.css$/i, /*include: [/node_modules/],*/ exclude: [/bootstrap.css$/, /font-awesome.css$/], issuer: [{ not: [{ test: /\.html$/i }] }], use: ["style-loader", ...cssLoaders] },
                { test: /\.css$/, include: [/bootstrap.css$/, /font-awesome.css$/], use: [{ loader: MiniCssExtractPlugin.loader }, ...cssLoaders] },
                { test: /\.scss$/i, issuer: /(\.html|empty-entry\.js)$/i, use: scssLoaders },
                { test: /\.scss$/i, issuer: /\.ts$/i, use: ["style-loader", ...scssLoaders] }
            ]
        },
        optimization: {
            splitChunks: {
                chunks: "all",
                // comment the following to avoid creatin a separate bundle for each npm module
                maxInitialRequests: Infinity,
                minSize: 0,
                cacheGroups: {
                    vendor: {
                        test: /[\\/]node_modules[\\/]/,
                        name(module) {
                            // get the name. E.g. node_modules/packageName/not/this/part.js
                            // or node_modules/packageName
                            const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

                            // npm package names are URL-safe, but some servers don't like @ symbols
                            return `npm.${packageName.replace('@', '')}`;
                        }
                    }
                }
            }
        },
        devtool: isDevBuild ? "source-map" : false,
        performance: {
            hints: false
        },
        plugins: [
            new CleanWebpackPlugin(),
            new webpack.DefinePlugin({ IS_DEV_BUILD: JSON.stringify(isDevBuild) }),
            new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }),
            new HtmlWebpackPlugin({ template: 'index.ejs', filename: "../../wwwroot/index.html", inject: false, metadata: {}, alwaysWriteToDisk: true }),
            new AureliaPlugin({ aureliaApp: "boot" }),
            new GlobDependenciesPlugin({ "boot": ["ClientApp/**/*.{ts,html}"] }),
            new ModuleDependenciesPlugin({}),
            new MiniCssExtractPlugin({
                filename: "[name].[hash].css",
                chunkFilename: "[name].[chunkhash].css"
            })
        ],
        devServer: {
            contentBase: "wwwroot/",
            compress: true,
            writeToDisk: true,
            hot: false
        }
    }];
};

我知道它应该查看 package.json,但我不擅长 webpack......这些天很难跨越一切......

如何修复此错误?

编辑

作为对@Krishna 的回答,我发布了运行结果: npm run webpack:debug

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'webpack:Debug'
1 verbose cli ]
2 info using npm@6.11.3
3 info using node@v12.12.0
4 verbose run-script [ 'prewebpack:Debug', 'webpack:Debug', 'postwebpack:Debug' ]
5 info lifecycle JobsLedger.API@0.0.1~prewebpack:Debug: JobsLedger.API@0.0.1
6 info lifecycle JobsLedger.API@0.0.1~webpack:Debug: JobsLedger.API@0.0.1
7 verbose lifecycle JobsLedger.API@0.0.1~webpack:Debug: unsafe-perm in lifecycle true
8 verbose lifecycle JobsLedger.API@0.0.1~webpack:Debug: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\simon\Documents\AURELIA\1.0 - JobsLedgerSPA -ASPNET CORE 3.1\JobsLedgerSPA\JobsLedger.API\node_modules\.bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Python27\;C:\Python27\Scripts;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\ProgramData\chocolatey\bin;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Users\simon\AppData\Local\Microsoft\WindowsApps;C:\Users\simon\.dotnet\tools;C:\Users\simon\AppData\Roaming\npm;C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE;
9 verbose lifecycle JobsLedger.API@0.0.1~webpack:Debug: CWD: C:\Users\simon\Documents\AURELIA\1.0 - JobsLedgerSPA -ASPNET CORE 3.1\JobsLedgerSPA\JobsLedger.API
10 silly lifecycle JobsLedger.API@0.0.1~webpack:Debug: Args: [ '/d /s /c', 'webpack --mode development' ]
11 silly lifecycle JobsLedger.API@0.0.1~webpack:Debug: Returned: code: 1  signal: null
12 info lifecycle JobsLedger.API@0.0.1~webpack:Debug: Failed to exec webpack:Debug script
13 verbose stack Error: JobsLedger.API@0.0.1 webpack:Debug: `webpack --mode development`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:210:5)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:210:5)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
14 verbose pkgid JobsLedger.API@0.0.1
15 verbose cwd C:\Users\simon\Documents\AURELIA\1.0 - JobsLedgerSPA -ASPNET CORE 3.1\JobsLedgerSPA\JobsLedger.API
16 verbose Windows_NT 10.0.18363
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "webpack:Debug"
18 verbose node v12.12.0
19 verbose npm  v6.11.3
20 error code ELIFECYCLE
21 error errno 1
22 error JobsLedger.API@0.0.1 webpack:Debug: `webpack --mode development`
22 error Exit status 1
23 error Failed at the JobsLedger.API@0.0.1 webpack:Debug script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

标签: webpack.net-coresingle-page-applicationwebpack-4

解决方案


"scripts": {
    "lint": "tslint --project tsconfig.json",
    "webpack:Debug": "webpack --mode development",
    "webpack:Release": "webpack --mode production",
    "webpack:watch": "webpack --mode development --watch"
  },

您的 package.json 没有任何带有 keyName 的脚本"webpack:dev"。要在开发模式下运行构建,请尝试运行npm run webpack:Debug


推荐阅读