创建配置文件webpack.config.js

  • webpack.config.js 根目录,与src文件夹同级
  • 作用: 指示 webpack 干哪些活(当你运行 webpack 指令时,会加载里面的配置)
  • 所有构建工具都是基于nodejs平台运行的~模块化默认采用commonjs。 ```javascript // resolve用来拼接绝对路径的方法 const { resolve } = require( ‘path’); // node 内置核心模块,用来处理路径问题。

module.s exports = { entry: ‘./src/js/index.js’, // 入口文件 output: { // 输出配置 filename: ‘./built.js’, // 输出文件名 path: resolve(__dirname, ‘build/js’) // 输出文件路径配置 }, // loader配置 module:{ rules:[] }, plugin:[], // plugin插件配置 mode: ‘development’ // development 开发环境 production 生产环境 };

  1. 执行命令
  2. ```shell
  3. (根目录) > webpack

执行效果与上一节相同

开发环境配置

目的:代码能运行,且不需要输入任何文件

  • 项目目录

image.png

  • 配置文件 ```javascript /* 开发环境配置:能让代码运行 运行项目指令:
    1. webpack 会将打包结果输出出去
    2. npx webpack-dev-server 只会在内存中编译打包,没有输出
    */

const { resolve } = require(‘path’); const HtmlWebpackPlugin = require(‘html-webpack-plugin’);

module.exports = { entry: ‘./src/js/index.js’, output: { filename: ‘js/built.js’, path: resolve(dirname, ‘build’) }, module: { rules: [ // loader的配置 { // 处理less资源 test: /.less$/, use: [‘style-loader’, ‘css-loader’, ‘less-loader’] }, { // 处理css资源 test: /.css$/, use: [‘style-loader’, ‘css-loader’] }, { // 处理图片资源 test: /.(jpg|png|gif)$/, loader: ‘url-loader’, options: { limit: 8 * 1024, name: ‘[hash:10].[ext]’, // 关闭es6模块化 esModule: false, outputPath: ‘imgs’ } }, { // 处理html中img资源 test: /.html$/, loader: ‘html-loader’ }, { // 处理其他资源 exclude: /.(html|js|css|less|jpg|png|gif)$/, loader: ‘file-loader’, options: { name: ‘[hash:10].[ext]’, outputPath: ‘media’ } } ] }, plugins: [ // plugins的配置 new HtmlWebpackPlugin({ template: ‘./src/index.html’ }) ], mode: ‘development’, devServer: { contentBase: resolve(dirname, ‘build’), compress: true, port: 3000, open: true } };

```

  • 执行指令:
    • 局部安装 npx webpack-dev-server
    • 全局安装 webpack-dev-server