搭建开发环境--热加载以及转换es6

2022-08-15 08:26:43 浏览数 (1)

安装node和npm后

1、 初始化npm环境,安装webpack

代码语言:javascript复制
npm init
npm install webpack webpack-cli --save-dev

根文件夹建立一个src文件夹,里面添加index.js文件,再在根目录添加webpack.dev.config.js

代码语言:javascript复制
module.exports = {
    entry: './src/index.js',
    output: {
        path: __dirname,
        filename: './release/bundle.js'
    }
}

npm run dev即可打包index

2、安装webpack-dev-server

代码语言:javascript复制
cnpm i webpack-dev-server html-webpack-plugin --save-dev

根目录创建index.html文件

webpack.dev.config.js代码更改为

代码语言:javascript复制
const path = require('path')
const HtmlWebpackPlugin =  require('html-webpack-plugin')

module.exports = {
    entry: './src/index.js',
    output: {
        path: __dirname,
        filename: './release/bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './index.html'
        })
    ],
    devServer: {
        contentBase: path.join(__dirname, './release'), // 根目录
        open: true, // 根目录自动打开浏览器
        port: 9000
    }
}

package.json代码更改

代码语言:javascript复制
{
  "name": "hot-loaded",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "dev": "webpack-dev-server --config ./webpack.dev.config.js --mode development"
  },
  "author": "Tony",
  "license": "ISC",
  "devDependencies": {
    "follow-redirects": "^1.5.9",
    "handle-thing": "^1.2.5",
    "html-webpack-plugin": "^3.2.0",
    "http-deceiver": "^1.2.7",
    "http-proxy": "^1.17.0",
    "mime": "^2.3.1",
    "node-forge": "^0.7.6",
    "spdy-transport": "^2.1.0",
    "webpack": "^4.22.0",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.9"
  }
}

然后执行cnpm i 再执行 npm run dev 即可看到在浏览器上自动打开。至此已经完成热加载

3、安装babel

代码语言:javascript复制
cnpm i babel-core babel-loader babel-polyfill babel-preset-es2015 babel-preset-latest --save-dev

index.js

代码语言:javascript复制
class Person {
    constructor(name){
        this.name = name;
    }
    getName(){
        return this.name;
    }
}

let p  = new Person('sdfdsd');
alert(p.getName());

根目录新建.babelrc

代码语言:javascript复制
{
    "presets": [
        "es2015", "latest"
    ],
    "plugins": [
        
    ]
}

webpack.dec,config.js

代码语言:javascript复制
const path = require('path')
const HtmlWebpackPlugin =  require('html-webpack-plugin')

module.exports = {
    entry: './src/index.js',
    output: {
        path: __dirname,
        filename: './release/bundle.js'
    },
    // es6转es5
    module: {
        rules: [{
            test: /.js?$/,
            exclude: /(node_modules)/,
            loader: 'babel-loader'
        }]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './index.html'
        })
    ],
    devServer: {
        contentBase: path.join(__dirname, './release'), // 根目录
        open: true, // 根目录自动打开浏览器
        port: 9000
    }
}

npm i babel-loader@7 --save-dev

npm run dev

即可正常转换es6

https://github.com/zyqq/hot-loaded

0 人点赞