上面我们已经讲解过了 webpack打包原理入门探究(一),可以看看如下文章
接着上一节课的目录来看看,这一节课的目录会有什么样的改变呢?新增了 dist,src/scripts,src/styles 目录
module.exports = {
entry: 'src/scripts/main.js', // 指定入口文件
output: {
path: 'dist/js',
filename: 'main.bundle.js'
}
}
{
"name": "webpackdemo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --mode development",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^3.2.0",
"style-loader": "^1.0.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10"
}
}
如果,我们不配置 webpack.config.js 的 entry,webpack 会报找不到入口,配置了入口之口,直接运行也会报错,是因为 webpack 解析不了相对路径,只能解析绝对路径,此时,webpack.config.js 需要修改一下了,我们需要 引入 path 来帮助我们解析 路径
let path = require('path')
function resolve(o) {
return path.resolve(__dirname, o)
}
module.exports = {
entry: resolve('src/scripts/main.js'), // 指定入口文件
output: {
path: resolve('dist/js'),
filename: 'main.bundle.js'
}
}
执行一下 npm run build,,执行成功了,在 dist 目录的 js 文件夹里生成了 mian.bundle.js
此时,我们需要利用webpack 一个 配置选项来配置指定 相应的 webpack config 文件
{
"name": "webpackdemo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --mode development",
"webpack.dev": "webpack --mode development --config webpack.dev.config.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^3.2.0",
"style-loader": "^1.0.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10"
}
}
请看 webpack.dev, 通过 --config 指定配置文件 为 webpack.dev.config.js,然后再执行
npm run webpack.dev
就可执行成功了