1 初始化,生成package.json文件:npm init -y
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
2 使用3版本初始化webpack工程:npm i -D webpack@3
- 生成node_modules文件夹
package.json中自动增加依赖devDependencies和scripts
{ "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "webpack": "^3.12.0" } }
- 在scripts中增加自定义的运行命令 "dev": "webpack" 如下:
{ "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "webpack": "^3.12.0" } }
3 配置webpack: webpack.config.js
const path=require('path')
module.exports={
entry: './src/main.js', //入口js文件
output:{
path: path.resolve(__dirname,'dist/appname/'),//输出到本地路径
filename: 'js/app.js',//输出子路径及文件名
publicPath: '/appname/' //拼接路径
}
}
publicPath说明:会在每个module->rules->xxx-loader->options->name前加上此处配置的路径,如:
{ test: /\.(eot|svg|ttf|woff|woff2)$/, use:[{ loader: 'file-loader', options:{ name: 'fonts/[name]_[hash:8].[ext]' } }] }
会把.eot, .svg, .ttf, .woff, .woff2文件输出到/dist/appname/fonts/xxx.xx中,并且会给资源的src或url前拼接上"/appname/"字符串
4 在src中写js代码
main.js
import a from './a'
import b from './b'
import c from './c'
a()
b()
c()
a.js
export default function a(){
console.log('a')
}
b.js
export default function b(){
console.log('b')
}
c.js
export default function c(){
console.log('c')
}
5 编译js:npm run dev,会在dist文件夹中生成app.js文件
6 引入到index.html中
<html>
<head>
<script type="text/javascript" src="../dist/app.js"></script>
</head>
</html>