手动构建Webpack开发环境
WebPack基础教程
Webpack开发环境配置
webpack+sass+babel+postcss配置
Webpack多页面配置
手动构建Webpack开发环境
-
初始化项目
$ npm init --yes
初始化完成以后,它会帮我们生成一个package.json文件,这是项目的基本信息
-
安装项目的依赖项
$ cnpm install webpack@3 webpack-dev-server@2 --save-dev
一定要记得, 这个地方后面跟着的是
--save-dev
代表的是开发环境依赖 -
新建文件夹src,在里面编写JS代码
//这是入口文件 //习惯性把webpack里面的入口文件叫main.js const Person = require('./Person.js'); var p = new Person("张三"); document.write(p.toString());
class Person { constructor(name) { this.name = name; } toString() { return `大家好:我是${this.name}`; } } //第一种模块化规范 CommonJs module.exports = Person;
-
配置webpack.config.dev.js
//开发环境下面的webpack配置项 //入口 输出 const path = require('path'); //这个config就是我们的webpack配置 var config = { entry: path.join(__dirname, "./src/main.js"), //webpack的入口 output: { filename: "bundle.js", path: path.join(__dirname, "/dist") }, devServer: { host: "0.0.0.0", //本机的所有IP port: 9999 //端口号 } } //这是webpack强制规定 module.exports = config;
-
配置webpack的启动命令
在package.json的
scripts
里面,去添加如下命令$ "dev":"webpack-dev-server --config webpack.config.dev.js "
执行启动命令
$ npm run dev
-
添加index.html文件
-
安装插件,让生成的JS代码自动的插入到我们的网页当中去
$ cnpm install html-webpack-plugin --save-dev
-
模块化的注意事项
export class Person { constructor(name) { this.name = name; } toString() { return `大家好:我是${this.name}`; } } //第一种模块化规范 CommonJs //module.exports = { Person }; export class Dog { toString() { return `我是一支狗`; } } export default class Student { toString() { return `我是一个学生`; } } //在ES6里面,每一个文件里面,默认只允许有一个 //默认导出对象 在导出的时候加上default就可以了
//这是入口文件 //习惯性把webpack里面的入口文件叫main.js // const Person = require('./Person.js'); //const { Person } = require('./Person.js'); import { Person, Dog } from "./Person.js"; import Student from './Person.js'; var p = new Person("张三"); document.write(p.toString()); console.log("李四"); document.write("王五"); var d = new Dog(); document.write(d.toString()); document.write('<hr>'); var s = new Student(); document.write(s.toString());
以上两个文件是ES6的模块化import与export在webpack中的体现关系
-
让webpack来处理我们的css/scss文件
loader 让 webpack 能够去处理那些非 JavaScript 文件(webpack 自身只理解 JavaScript)。loader 可以将所有类型的文件转换为 webpack 能够处理的有效模块,然后你就可以利用 webpack 的打包能力,对它们进行处理。
我们需要安装第三方的模块
style-loader
,css-loader
//开发环境下面的webpack配置项 //入口 输出 const path = require('path'); //html-webpack-plugin这个插件它主要的作用就是生成html,然后把自动生成的JS文件插入到 //我们的html里面 const HTMLPlugin = require('html-webpack-plugin'); //这个config就是我们的webpack配置 var config = { entry: path.join(__dirname, "./src/main.js"), //webpack的入口 output: { filename: "bundle.js", path: path.join(__dirname, "/dist") }, devServer: { host: "0.0.0.0", //本机的所有IP port: 9999 //端口号 }, //配置我们的loader的 module: { rules: [{ test: /\.css$/, use: [ "style-loader", "css-loader" ] }, { test: /\.scss$/, use: [ "style-loader", "css-loader", "sass-loader" ] }] }, plugins: [ new HTMLPlugin({ template: "index.html", //按照那一个模板去生成我们的HTML文件 inject: true //打包好的js文件是否自动的插入到html中 }) ] } //这是webpack强制规定 module.exports = config;