webpack打包中path.resolve和__dirname的含义

本文深入解析了Webpack配置中path.resolve和__dirname的使用方法及意义,详细介绍了Node.js核心模块path的功能,包括如何生成绝对路径,以及__dirname和__filename在模块加载过程中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在webpack打包中,我们经常会有这样的配置,

const path = require('path');

module.exports = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'), // 对这一行代码有疑问
    filename: 'my-first-webpack.bundle.js'
  }
};

那么我们来看一下path.resolve和__dirname的含义。

1、path是node中的一个核心模块。

官网文档解释如下:
path 模块提供了一些实用工具,用于处理文件和目录的路径。 可以使用以下方式访问它:

const path = require('path');

引入之后我们看一下path.resolve()方法

path.resolve([...paths])

…paths 路径或路径片段的序列。
返回: <string>
path.resolve() 方法会将路径或路径片段的序列解析为绝对路径。
给定的路径序列会从右到左进行处理,后面的每个 path 会被追加到前面,直到构造出绝对路径。 例如,给定的路径片段序列:/目录1、 /目录2、 目录3,调用 path.resolve(’/目录1’, ‘/目录2’, ‘目录3’) 会返回 /目录2/目录3,因为 ‘目录3’ 不是绝对路径,但 ‘/目录2’ + ‘/’ + ‘目录3’ 是。

如果在处理完所有给定的 path 片段之后还未生成绝对路径,则会使用当前工作目录。

生成的路径会被规范化,并且尾部的斜杠会被删除(除非路径被解析为根目录)。

零长度的 path 片段会被忽略。

如果没有传入 path 片段,则 path.resolve() 会返回当前工作目录的绝对路径。

path.resolve('/目录1/目录2', './目录3');
// 返回: '/目录1/目录2/目录3'

path.resolve('/目录1/目录2', '/目录3/目录4/');
// 返回: '/目录3/目录4'

path.resolve('目录1', '目录2/目录3/', '../目录4/文件.gif');
// 如果当前工作目录是 /目录A/目录B,
// 则返回 '/目录A/目录B/目录1/目录2/目录4/文件.gif'
2、__dirname

– directory(目录)name === 目录名
当前模块的目录名。 相当于 __filename 的 path.dirname()。
示例,从 /Users/mjr 运行 node example.js:

console.log(__dirname);
// 打印: /Users/mjr
console.log(path.dirname(__filename));
// 打印: /Users/mjr
3、__filename

– file(文件)name === 文件名
当前模块的文件名。 这是当前的模块文件的绝对路径(符号链接会被解析)。

对于主程序,这不一定与命令行中使用的文件名相同。

有关当前模块的目录名,参见 __dirname。

示例:

从 /Users/mjr 运行 node example.js:

console.log(__filename);
// 打印: /Users/mjr/example.js
console.log(__dirname);
// 打印: /Users/mjr

给定两个模块:a 和 b,其中 b 是 a 的依赖文件,且目录结构如下:

/Users/mjr/app/a.js
/Users/mjr/app/node_modules/b/b.js
b.js 中的 __filename 的引用会返回 /Users/mjr/app/node_modules/b/b.js,而 a.js 中的 __filename 的引用会返回 /Users/mjr/app/a.js。

将上述修改整合到我提供的文件中 const path = require('path'); const fs = require('fs'); const WEB_SITE = 'mobile'; const { ZipUpload } = require("@hyfe/hy-utils").default.fs; const TYPE_ENV = process.env.TYPE_ENV; const envSelect = process.env.envSelect; let destPath = "../../s2b/s2b/mobile/dist_mobile/h5" const buildAnalyzeFlag = process.env.analyze; const prodFlag = TYPE_ENV === 'prod'; // ==================== Webpack 5 兼容性修复 ==================== const webpackSourcesPath = require.resolve('webpack-sources'); const webpackSourcesDir = path.dirname(webpackSourcesPath); // ============================================================ const config = { projectName: 'mini-program-taro', date: '2019-5-22', designWidth: 750, deviceRatio: { 640: 2.34 / 2, 750: 1, 828: 1.81 / 2, }, sourceRoot: 'src', outputRoot: `dist/${process.env.TARO_ENV}`, // ==================== 持久化缓存配置 ==================== cache: { enable: true, type: 'filesystem', buildDependencies: { config: [__filename] } }, // ===================================================== alias: { '@/assets': path.resolve(__dirname, '..', 'src/assets'), '@/tpl-assets': path.resolve(__dirname, '..', 'node_modules/@hyfe/ui-taro/lib/assets/templates'), '@/pages': path.resolve(__dirname, '..', 'src/pages'), '@/service': path.resolve(__dirname, '..', 'src/service'), '@/redux': path.resolve(__dirname, '..', 'src/redux'), '@/utils': path.resolve(__dirname, '..', 'src/utils'), '@/libs': path.resolve(__dirname, '..', 'src/libs'), 'taro-ui$': 'taro-ui/lib/index', api: path.resolve(__dirname, '..', 'src/webapi'), wmkit: path.resolve(__dirname, '..', 'src/wmkit/common'), config: path.resolve(__dirname, '..', 'src/wmkit/config'), immutable: path.resolve(__dirname, '..', 'src/wmkit/common/immutable.min.js'), '@/*': path.resolve(__dirname, '..', 'src/*'), // ==================== Webpack 兼容性别名 ==================== 'webpack/sources': webpackSourcesDir }, terser: { enable: true, config: { warnings: false, compress: { drop_debugger: true, drop_console: false, }, }, }, csso: { enable: true, config: { restructure: true, }, }, sass: { resource: [ path.resolve(__dirname, '..', 'src/pages/common/style/swipe.scss'), path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/modal.scss'), path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/switch.scss'), path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/tab-bar.scss'), path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/badge.scss'), path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/noticebar.scss'), ], projectDirectory: path.resolve(__dirname, '..'), data: '$nav-height: 48px;', }, defineConstants: { process: { env: { TYPE_ENV: JSON.stringify(process.env.TYPE_ENV), envSelect: JSON.stringify(process.env.envSelect), TARO_ENV: JSON.stringify(process.env.TARO_ENV), analyze: JSON.stringify(process.env.analyze), } }, }, compiler: { type: 'webpack5', prebundle: { enable: false } }, copy: { patterns: [], options: {}, }, plugins: [ [ "@tarojs/plugin-framework-react", { reactRefresh: true // 确保启用热更新 } ], ["babel-plugin-import", { libraryName: "taro-ui", customName: (name, file) => { const nameSection = name.split('-') if (nameSection.length === 4) { nameSection.pop() } const pathMap = { 'tabs/pane': 'tabs-pane', 'modal-action': 'modal/action', 'modal-content': 'modal/content', 'modal-header': 'modal/header', 'badge': 'badge', 'switch': 'switch', 'tab-bar': "tab-bar", 'progress': 'progress', 'icon': 'icon' } const path = nameSection.slice(1).join('-'); return `taro-ui/lib/components/${pathMap[path] || path}`; }, style: (name) => { if (name.includes('/modal')) { return 'taro-ui/dist/style/components/modal.scss' } const wholePath = name.split('/') const compName = wholePath[wholePath.length - 1] const fix = { 'tabs-pane': 'tabs', 'modal/action': 'modal', 'modal/header': 'modal', 'modal/content': 'modal', 'badge': 'badge', 'switch': 'switch', 'tab-bar': "tab-bar", 'progress': 'progress', 'icon': 'icon' }[compName] return `taro-ui/dist/style/components/${fix || compName}.scss` } }] ], framework: 'react', mini: { enableSourceMap: !prodFlag, miniCssExtractPluginOption: { ignoreOrder: true }, compile: {}, postcss: { pxtransform: { enable: true, config: { selectorBlackList: ['body'] }, }, url: { enable: true, config: { limit: 1024, }, }, cssModules: { enable: false, config: { namingPattern: 'module', generateScopedName: '[name]__[local]___[hash:base64:5]', }, }, }, webpackChain(chain, webpack) { // ==================== Webpack 兼容性修复 ==================== chain.resolve.alias.set('webpack/sources', webpackSourcesDir); chain.optimization.minimize(true); buildAnalyzeFlag && chain.plugin('analyzer') .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, []); chain.plugin('ignore').use(webpack.IgnorePlugin, [{ resourceRegExp: /^\.\/locale$/, contextRegExp: /moment$/ }]); chain.merge({ optimization: { splitChunks: { cacheGroups: { // 保留原有缓存组配置... }, }, }, }); }, lessLoaderOption: { paths: [path.resolve(__dirname, 'node_modules'), path.resolve(__dirname, '..', 'src')], }, imageUrlLoaderOption: { esModule: false, }, }, h5: { publicPath: `/${WEB_SITE}/`, staticDirectory: 'static', esnextModules: ['taro-ui', '@hyfe/ui-taro', '@hyfe'], output: { filename: 'js/[name].[hash].js', chunkFilename: 'js/[name].[chunkhash].js', }, miniCssExtractPluginOption: { filename: 'css/[name].[hash].css', chunkFilename: 'css/[name].[chunkhash].css', ignoreOrder: true }, router: { basename: `/${WEB_SITE}/`, mode: 'browser', }, enableSourceMap: !prodFlag, postcss: { autoprefixer: { enable: true, config: {}, }, url: { enable: true, config: { limit: 1024, }, }, cssModules: { enable: false, config: { namingPattern: 'module', generateScopedName: '[name]__[local]___[hash:base64:5]', }, }, }, webpackChain(chain) { // ==================== Webpack 兼容性修复 ==================== chain.resolve.alias.set('webpack/sources', webpackSourcesDir); chain.plugin('htmlWebpackPlugin').tap((args) => { args[0].publicPath = `/${WEB_SITE}/`; return args; }); chain.module.rule('script') .exclude .add(/app\.config\.ts$/) chain.merge({ optimization: { splitChunks: { cacheGroups: { lodash: { name: 'lodash', priority: 1000, test(module) { return /[\\/]node_modules[\\/]lodash/.test(module.resource); }, }, }, }, } }); if (prodFlag) { chain.plugin('after-build-plugin') .use(new ZipUpload({ envCode: envSelect, scriptPath: path.resolve(__dirname, './zip_upload.sh'), src: path.resolve(__dirname, '../dist/h5'), dest: path.resolve(__dirname, destPath) })); } }, commonChunks(commonChunks) { commonChunks.push('lodash'); return commonChunks; }, lessLoaderOption: { paths: [path.resolve(__dirname, 'node_modules'), path.resolve(__dirname, '..', 'src')] }, imageUrlLoaderOption: { esModule: false, }, devServer: { host: '0.0.0.0', port: '8080', open: `/${WEB_SITE}/`, }, }, }; module.exports = function (merge) { return merge({}, config, require('./build')); };
最新发布
07-02
其中需要在 // config/index.js中修改的东西 下面是已有的文件内容 整合梳理一下完整输出const path = require('path'); const fs = require('fs'); const WEB_SITE = 'mobile'; const { ZipUpload } = require("@hyfe/hy-utils").default.fs; const TYPE_ENV = process.env.TYPE_ENV; const envSelect = process.env.envSelect; let destPath = "../../s2b/s2b/mobile/dist_mobile/h5" const buildAnalyzeFlag = process.env.analyze; const prodFlag = TYPE_ENV === 'prod'; // ==================== Webpack 5 兼容性修复 ==================== const webpackSourcesPath = require.resolve('webpack-sources'); const webpackSourcesDir = path.dirname(webpackSourcesPath); // ============================================================ const config = { projectName: 'mini-program-taro', date: '2019-5-22', designWidth: 750, deviceRatio: { 640: 2.34 / 2, 750: 1, 828: 1.81 / 2, }, sourceRoot: 'src', outputRoot: `dist/${process.env.TARO_ENV}`, // ==================== 持久化缓存配置 ==================== cache: { enable: true, type: 'filesystem', buildDependencies: { config: [__filename] } }, // ===================================================== alias: { '@/assets': path.resolve(__dirname, '..', 'src/assets'), '@/tpl-assets': path.resolve(__dirname, '..', 'node_modules/@hyfe/ui-taro/lib/assets/templates'), '@/pages': path.resolve(__dirname, '..', 'src/pages'), '@/service': path.resolve(__dirname, '..', 'src/service'), '@/redux': path.resolve(__dirname, '..', 'src/redux'), '@/utils': path.resolve(__dirname, '..', 'src/utils'), '@/libs': path.resolve(__dirname, '..', 'src/libs'), 'taro-ui$': 'taro-ui/lib/index', api: path.resolve(__dirname, '..', 'src/webapi'), wmkit: path.resolve(__dirname, '..', 'src/wmkit/common'), config: path.resolve(__dirname, '..', 'src/wmkit/config'), immutable: path.resolve(__dirname, '..', 'src/wmkit/common/immutable.min.js'), '@/*': path.resolve(__dirname, '..', 'src/*'), // ==================== Webpack 兼容性别名 ==================== 'webpack/sources': webpackSourcesDir }, terser: { enable: true, config: { warnings: false, compress: { drop_debugger: true, drop_console: false, }, }, }, csso: { enable: true, config: { restructure: true, }, }, sass: { resource: [ path.resolve(__dirname, '..', 'src/pages/common/style/swipe.scss'), path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/modal.scss'), path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/switch.scss'), path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/tab-bar.scss'), path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/badge.scss'), path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/noticebar.scss'), ], projectDirectory: path.resolve(__dirname, '..'), data: '$nav-height: 48px;', }, defineConstants: { process: { env: { TYPE_ENV: JSON.stringify(process.env.TYPE_ENV), envSelect: JSON.stringify(process.env.envSelect), TARO_ENV: JSON.stringify(process.env.TARO_ENV), analyze: JSON.stringify(process.env.analyze), } }, }, compiler: { type: 'webpack5', prebundle: { enable: false } }, copy: { patterns: [], options: {}, }, plugins: [ [ "@tarojs/plugin-framework-react", { reactRefresh: true // 确保启用热更新 } ], ["babel-plugin-import", { libraryName: "taro-ui", customName: (name, file) => { const nameSection = name.split('-') if (nameSection.length === 4) { nameSection.pop() } const pathMap = { 'tabs/pane': 'tabs-pane', 'modal-action': 'modal/action', 'modal-content': 'modal/content', 'modal-header': 'modal/header', 'badge': 'badge', 'switch': 'switch', 'tab-bar': "tab-bar", 'progress': 'progress', 'icon': 'icon' } const path = nameSection.slice(1).join('-'); return `taro-ui/lib/components/${pathMap[path] || path}`; }, style: (name) => { if (name.includes('/modal')) { return 'taro-ui/dist/style/components/modal.scss' } const wholePath = name.split('/') const compName = wholePath[wholePath.length - 1] const fix = { 'tabs-pane': 'tabs', 'modal/action': 'modal', 'modal/header': 'modal', 'modal/content': 'modal', 'badge': 'badge', 'switch': 'switch', 'tab-bar': "tab-bar", 'progress': 'progress', 'icon': 'icon' }[compName] return `taro-ui/dist/style/components/${fix || compName}.scss` } }] ], framework: 'react', mini: { enableSourceMap: !prodFlag, miniCssExtractPluginOption: { ignoreOrder: true }, compile: {}, postcss: { pxtransform: { enable: true, config: { selectorBlackList: ['body'] }, }, url: { enable: true, config: { limit: 1024, }, }, cssModules: { enable: false, config: { namingPattern: 'module', generateScopedName: '[name]__[local]___[hash:base64:5]', }, }, }, webpackChain(chain, webpack) { // ==================== Webpack 兼容性修复 ==================== chain.resolve.alias.set('webpack/sources', webpackSourcesDir); chain.optimization.minimize(true); buildAnalyzeFlag && chain.plugin('analyzer') .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, []); chain.plugin('ignore').use(webpack.IgnorePlugin, [{ resourceRegExp: /^\.\/locale$/, contextRegExp: /moment$/ }]); chain.merge({ optimization: { splitChunks: { cacheGroups: { // 保留原有缓存组配置... }, }, }, }); }, lessLoaderOption: { paths: [path.resolve(__dirname, 'node_modules'), path.resolve(__dirname, '..', 'src')], }, imageUrlLoaderOption: { esModule: false, }, }, h5: { publicPath: `/${WEB_SITE}/`, staticDirectory: 'static', esnextModules: ['taro-ui', '@hyfe/ui-taro', '@hyfe'], output: { filename: 'js/[name].[hash].js', chunkFilename: 'js/[name].[chunkhash].js', }, miniCssExtractPluginOption: { filename: 'css/[name].[hash].css', chunkFilename: 'css/[name].[chunkhash].css', ignoreOrder: true }, router: { basename: `/${WEB_SITE}/`, mode: 'browser', }, enableSourceMap: !prodFlag, postcss: { autoprefixer: { enable: true, config: {}, }, url: { enable: true, config: { limit: 1024, }, }, cssModules: { enable: false, config: { namingPattern: 'module', generateScopedName: '[name]__[local]___[hash:base64:5]', }, }, }, webpackChain(chain) { // ==================== Webpack 兼容性修复 ==================== chain.resolve.alias.set('webpack/sources', webpackSourcesDir); chain.plugin('htmlWebpackPlugin').tap((args) => { args[0].publicPath = `/${WEB_SITE}/`; return args; }); chain.module.rule('script') .exclude .add(/app\.config\.ts$/) chain.merge({ optimization: { splitChunks: { cacheGroups: { lodash: { name: 'lodash', priority: 1000, test(module) { return /[\\/]node_modules[\\/]lodash/.test(module.resource); }, }, }, }, } }); if (prodFlag) { chain.plugin('after-build-plugin') .use(new ZipUpload({ envCode: envSelect, scriptPath: path.resolve(__dirname, './zip_upload.sh'), src: path.resolve(__dirname, '../dist/h5'), dest: path.resolve(__dirname, destPath) })); } }, commonChunks(commonChunks) { commonChunks.push('lodash'); return commonChunks; }, lessLoaderOption: { paths: [path.resolve(__dirname, 'node_modules'), path.resolve(__dirname, '..', 'src')] }, imageUrlLoaderOption: { esModule: false, }, devServer: { host: '0.0.0.0', port: '8080', open: `/${WEB_SITE}/`, }, }, }; module.exports = function (merge) { return merge({}, config, require('./build')); };
07-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值