webpack 图片的打包
1. 在img文件夹下随便找一个小一点的图片放进去.
2.修改entry.js
require('../css/index.css'); var demo1 = require('../js/demo1.js'); var demo2 = require('../js/demo2.js'); demo1.init(); demo2.init(); var oImg = new Image(); oImg.src = require('../img/1.gif');//当成模块引入图片 document.body.appendChild(oImg);
由于我们引入的是静态资源, 在webpack.config.js中修改一下
module.exports = { entry : './src/js/entry.js', output : { filename : 'index.js', publicPath: __dirname + '/out',//添加静态资源, 否则会出现路径错误 path : __dirname + '/out' }, module : { rules: [ {test: /.js$/, use: ['babel-loader']}, {test: /.css$/, use: ['style-loader', 'css-loader']},/*解析css, 并把css添加到html的style标签里*/ //{test: /.css$/, use: ExtractTextPlugin.extract({fallback: 'style-loader',use: 'css-loader'})},/*解析css, 并把css变成文件通过link标签引入*/ {test: /.(jpg|png|gif|svg)$/, use: ['url-loader?limit=8192&name=./[name].[ext]']},/*解析图片*/ {test: /.less$/, use: ['style-loader', 'css-loader', 'less-loader']}/*解析less, 把less解析成浏览器可以识别的css语言*/ ] }, }
自己webpack看看效果
webpack服务器
首先先定位目录输入命令 npm install webpack-dev-server -g
, 修改webpack.config.js文件
publicPath: 'http://localhost:8080/out',
html文件所引用的目录也要更改:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>text</title> <link rel="stylesheet" href="http://localhost:8080/out/index.css"> </head> <body> <a href="http://localhost:8080/index2.html">11</a> <div class="demo1"></div> <div class="demo2"></div> <script src="http://localhost:8080/out/common.js"></script> <script src="http://localhost:8080/out/index.js"></script> </body> </html>
webpack-dev-server一下看看效果