path.join([path1],[path2])
path.join()方法可以丽娜姐任意多个路径字符串。
var path = require('path');
//合法的字符串连接
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
// 连接后
'/foo/bar/baz/asdf'
//不合法的字符串将抛出异常
path.join('foo', {}, 'bar')
// 抛出的异常 TypeError: Arguments to path.join must be strings'
path.resolve([from…],to)
path.resolve()方法可以将多个路径解析为一个规范化的绝对路径。
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
相当于
//进入到foo/bar文件夹中
cd foo/bar
//在foo/bar文件夹中,转到进入tmp/file文件夹
cd /tmp/file/
//进入上一级目录,即tmp/目录下
cd ..
//进入tmp/a/../subfile
cd a/../subfile
pwd
列子:
path.resolve('/foo/bar', './baz')
// 输出结果为
'/foo/bar/baz'
path.resolve('/foo/bar', '/tmp/file/')
// 输出结果为
'/tmp/file'
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// 当前的工作路径是 /home/itbilu/node,则输出结果为
'/home/itbilu/node/wwwroot/static_files/gif/image.gif'
对比
const path = require('path');
let myPath = path.join(__dirname,'/img/so');
let myPath2 = path.join(__dirname,'./img/so');
let myPath3 = path.resolve(__dirname,'/img/so');
let myPath4 = path.resolve(__dirname,'./img/so');
console.log(__dirname); //D:\myProgram\test
console.log(myPath); //D:\myProgram\test\img\so
console.log(myPath2); //D:\myProgram\test\img\so
console.log(myPath3); //D:\img\so<br>
console.log(myPath4); //D:\myProgram\test\img\so
webpack.config.js
/*
1. path.resolve是node.js的path方法,把一个路径或路径片段的序列解析为一个绝对路径,path.resolve([…paths])里的每个参数都类似在当前目录执行一个cd操作,从左到右执行,返回的是最后的当前目录
2. process.cwd() 方法返回 Node.js 进程当前工作的目录
3. __filename 也是node的全局变量 Node.js中,在任何模块文件内部,可以使用__filename变量获取当前模块文件的带有完整绝对路径的文件名
4. __dirname是node.js的一个全局变量,用于指向当前执行脚本(dirname.js)所在的目录路径,而且是绝对路径。
*/
var webpack = require("webpack");
var path = require("path");
var pathMap = require('./src/pathmap.json');
var srcDir = path.resolve(process.cwd(), 'src');
var nodeModPath = path.resolve(__dirname, './node_modules');
module.exports = {
entry: "./src/js/index.js",//入口js,可为数组
output: {//指示 webpack 如何去输出、以及在哪里输出你的「bundle、asset 和其他你所打包或使用 webpack 载入的任何内容
path: path.join(__dirname, "dist"),
filename: "bundle.js"
},
module: {
rules: [
{
test:/\.css$/,
use:[
"style-loader",
"css-loader",
]
}
]
},
resolve: {//设置模块如何被解析
extensions: ['.js',"",".css"],//自动解析确定的扩展。默认值为:[".js",".json"]
modules: [srcDir,nodeModPath],//告诉 webpack 解析模块时应该搜索的目录。
alias: pathMap,// import 或 require 的别名,来确保模块引入变得更简单
publicPath: '/'
}
}