loading...

1

webpack使用

html读完大概需要6分钟

  • 发布时间:2017-07-30 22:41 星期日
  • 刘伟波
  • 692
  • 更新于2017-11-22 16:48 星期三

webpack使用

1.//全局安装

npm install -g webpack

//安装到你的项目目录

npm install --save-dev webpack

2.npm init

3.package.json

{
"name": "webpack-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --open",
"watch": "webpack --watch",
"api": "json-server --watch db.json",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^3.8.1"
},
"dependencies": {
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.28.7",
"html-webpack-plugin": "^2.30.1",
"json-server": "^0.12.1",
"style-loader": "^0.19.0",
"webpack-dev-server": "^2.9.4"
}
}

npm start 开启热加载

npm run api 启用 json-server的json数据


4.webpack.config.js

const path=require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack=require('webpack');
const CleanWebpackPlugin=require('clean-webpack-plugin');
module.exports={
entry:'./src/index.js',
output:{
filename:'bundle.[hash:7].js',
path:path.resolve(__dirname+'/dist')
},
module: {
rules: [
{
test: /\.css$/,
use: [
{ loader: 'style-loader'},
{
loader: 'css-loader',
options: {
modules: true
}
}
]
}
]
},
plugins:[
new CleanWebpackPlugin(['dist']), //删除目录
new HtmlWebpackPlugin({template:'./src/index.html'}), //把生成的js文件引入
new webpack.HotModuleReplacementPlugin() //模块热替换
],
devtool:'inline-source-map', //inline-source-map 开发模式,有注释内联模式 source-map 上线模式
//http://www.css88.com/doc/webpack/configuration/dev-server/
devServer:{
contentBase:'./dist',
port:'8081',
hot:true,
disableHostCheck:true, //当设置为true时,此选项将绕过主机检查。这是不推荐使用的应用程序,不检查主机的DNS重新绑定攻击是脆弱的。
historyApiFallback:true, //任意的 404 响应都可能需要被替代为 index.html
proxy: {
"/api": {
target: "http://localhost:3000",
pathRewrite: {"^/api" : ""}
}
}
}
};


5.index.js

import { toUpper } from "./until";
import { hmr } from "./hmr";
import './index.css'


function createElement() {
let ele=document.createElement('div');
ele.innerHTML=toUpper('hello world!!!!!!!!!!!!!');
// throw new Error('报错');

let btn=document.createElement('button');
btn.innerHTML='点基触发';
btn.classList.add('btn');

ele.appendChild(btn);
return ele;
}

let ele=createElement();
document.body.appendChild(ele);

let btn=document.querySelector('button');
function append() {
ele.appendChild(hmr())
}
btn.addEventListener('click',append,false);

if(module.hot){ //如果这个模块启用了热更新
module.hot.accept('./hmr',function () {

})
}

// FETCH json-server的数据获取
fetch('/api/posts').then(function (res) {
res.json().then(function (data) {
console.log(data);
})
})





你可能感兴趣的文章

    发表评论

    评论支持markdown,评论内容不能超过500字符
    关于技术问题或者有啥不懂的都可以来 我的视频空间 提问, 推荐作者总结知识点 前端知识体系, 感謝支持!