使用相对路径为长路径配置npm&webpack Win10

时间:2020-11-07 11:51:38

标签: npm webpack config long-path

当前 webpack捆绑项目文件夹结构(win10)
root_folder \
| --node_modules
| --src
| --index.js
| --template.html
| --package.json
| --webpack.config.js

index.js 的内容:
console.log("Hello webpack");

template.html

的内容
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title><%= htmlWebpackPlugin.options.title %></title>
    </head>
    <body>
        <div id="root"></div>
    </body>
    </html>

package.json的内容:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "dependencies": {},
  "devDependencies": {
    "html-webpack-plugin": "^4.5.0",
    "webpack": "^5.4.0",
    "webpack-cli": "^4.2.0",
    "webpack-dev-server": "^3.11.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

webpack.config.js的内容:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: path.resolve(__dirname, './src/index.js'),
    },
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js',
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'webpack Boilerplate',
            template: path.resolve(__dirname, './src/template.html'), // template file
            filename: 'index.html', // output file
        }),
    ]
};

如何使此文件夹完全可移植,即在运行npx webpacknpm run build时,无论使用C:\root_folder\还是C:\very\longpath\root_folder,这始终可以很好地运行。
npx webpack的示例中成功运行了C:\root_folder\,然后将** root_folder **像它一样复制到了D:\testing\root_folder\中,并从npx webpack运行D:\testing\root_folder\时工作,显然表明它是便携式的。
简介:如果webpack捆绑项目的根文件夹属于其他项目,则将其存储在自己的项目子文件夹中会很有帮助,因此有时可以在嵌套文件夹中包含root_folder很有用。
问题:是否有一种方法可以使用简单的npm脚本甚至npx命令来解决Windows中具有本地路径的所有root_folder /脚本,因此对于长路径不会返回错误?
当前答案:很好的发现是将嵌套的root_folder复制到临时C:\temp\root_folder,然后从那里进行所有npm webpack处理以及模块捆绑。

1 个答案:

答案 0 :(得分:0)

所以在这里起作用的答案是挂载项目目录,然后从那里运行构建。

所有必要的是拥有以下npm脚本(在package.json中):

"scripts": {
    "test": "ECHO \"Error: no test specified\" && EXIT 1",
    "build": "(IF EXIST \"%CD%/dist\" RMDIR dist /S /Q) && webpack",
    "nestingcompliance:build": "SUBST Z: \"%CD%\" && PUSHD Z: && npm run build && POPD && SUBST Z: /D"
  }

然后在cmd行中运行:

npm run nestingcompliance:build