搭建一个属于自己的webpack config(-)

搭建一个属于自己的webpack config(-)

前期准备

环境说明

  • mac 10.12.6
  • node v8.8.1
  • npm 5.4.2

全局安装下webpack、webpack-dev-server

npm i webpack webpack-dev-server -g

对应版本

  • webpack@2.7.0
  • webpack-dev-server@2.9.5

初始化

	mkdir reactStudio
	cd reactStudio
	npm init -y

新建webpack.config.js 文件

const path = require('path')
module.exports={
    entry:{
        main:'./src/index.js' //编译的入口代码。对应的key就是编译出来的name
    },
    output:{
        filename: 'js/[name].js',//编译出来的文件名称
        publicPath: '/',//提供对外提供服务的地址
        path:path.resolve(__dirname,'dist')//编译后存放文件的绝对地址
    }
}

设置webpack 的入口文件为src/index.js 以及 编译后的文件名称和位置

设置npm scripts

{
  "name": "reactStudio",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --content-base public",//这里指定serve 对应的文件价
    "build": "webpack -p",生产环境的编译
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

这样运行 npm start 等于启动项目。npm run build 编译项目。通过这样的配置可以约定俗成一套命令,为以后自动化代码检测、测试、部署提供支持。

好了,我们新建一个src文件夹,再创建一个index.js,内容如下

alert('Hello Webpack')

以及新建public文件夹,创建index.html,内容如下

<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>测试</title>
</head>
<body>
     <div id="main">Hello webpack</div>
    <script src="js/main.js"></script>
</body>
</html>

这里的js引用路径和webpack 配置文件中output.publicPath 相关,详细说明查看webpack 配置说

这时候在当前文件夹的terminal 下执行npm start 就应该可以看到alert了。

下一步我们去支持es6语法

我们先修改src/index.js

let obj = {a:4,b:5}
let newObj = {...obj,c:7,b:8};
console.log(newObj)

如果你还在运行npm start,你应该可以看到

webpack: Compiling...
Hash: webpack: Failed to compile.
68167a5bd4e0b1a8e487
Version: webpack 2.7.0
Time: 8ms
     Asset    Size  Chunks                    Chunk Names
js/main.js  323 kB       0  [emitted]  [big]  main
chunk    {0} js/main.js (main) 318 kB [entry] [rendered]
    [2] ./src/index.js 267 bytes {0} [built] [failed] [1 error]
   [15] (webpack)/hot nonrecursive ^\.\/log$ 160 bytes {0} [built]
     + 23 hidden modules

ERROR in ./src/index.js
Module parse failed: /Users/rancho/Documents/studio/react-pass-value/src/index.js Unexpected token (2:14)
You may need an appropriate loader to handle this file type.
| let obj = {a:4,b:5}
| let newObj = {...obj,c:7,b:8};
| console.log(newObj)
 @ multi (webpack)-dev-server/client?http://localhost:8081 ./src/index.js

错误的意思是在解析src/index.js 文件时,出现未知的符号,我们需要加载一个合适的loader 去处理这种文件。我们知道文件类型没有变化,只是语法错误,这时候我们就要引用babel的编译了

修改webpack.config.js 增加一个module 节点

module: {
        rules: [
            {
                test: /\.(js|jsx)$/,//支持js and jsx 后缀
                include: path.resolve(__dirname, 'src'),//只编译src里面的文件里面的js
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            babelrc: false,
                            presets: [
                                'babel-preset-env',
                                'babel-preset-stage-0',
                            ],
                            plugins: ['transform-runtime'],//这样就不用引用babel-polyfill
                            cacheDirectory: true,
                        },
                    },
                ]
            }

        ]
    }

rule的include 和exclude 非必须,但是设置会优化webpack 编译的速度

babel-plugins 有增加一个 transform-runtime 这样就不用引用babel-polyfill。babel-polyfill 扩展很多原始的方法,具体查看 babel-polyfill

安装相关依赖
npm i babel-core babel-plugin-transform-runtime babel-preset-stage-0 babel-preset-env

重启命令后可以在页面的console 中看到

{a:4,b:8,c:7}

这里我们设置preset 为 babel-preset-env ,是因为 这个preset 可以根据你支持的环境去提供你需要的plugin,就不需要特别去配置 babel-preset-es2015, babel-preset-es2016, and babel-preset-es2017 这些了。详细配置查看.

支持react 的语法

新建一个src/Hello.jsx 文件

import React,{Component} from 'react'

export default class HelloReact extends Component{
    render(){
        return (
            <div>就是爱你!</div>
        )
    }
}

在src/index.js 引用并渲染出来

import React from 'react'
import ReactDOM from 'react-dom';
import Hello from './Hello.jsx'
let obj = {a:4,b:5}
let newObj = {...obj,c:7,b:8};
console.log(newObj)

ReactDOM.render(<Hello />, document.getElementById('main'));

在webpack.config.js 里面增加 babel-preset-react

presets: [
    'babel-preset-env',
    'babel-preset-react',
    'babel-preset-stage-0',
],

在此过程可能遇到的问题。

  1. import Hello from './Hello.jsx' 必须要加后缀jsx。否则会提示文件没有找到。解决方案在webpack.config.js 加入
resolve: {
        extensions: [
            '.js', '.jsx'//设置webpack 解析后缀名称,这样webpack就会自动寻找有该后缀的文件。
        ]
    },
  1. 有时候引用地址可能写错大小写,但是提示内容不够直观。比如·import React,{Component} from 'React'· 这时候也会报错。可以添加
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
 plugins: [
        new CaseSensitivePathsPlugin()
    ],

这样错误信息就更加清晰了

 [CaseSensitivePathsPlugin] `/node_modules/React/index.js` does not match the corresponding path on disk `react`.

有问题可以评论交流

posted @ 2017-12-01 10:45  yo水平  阅读(450)  评论(0编辑  收藏  举报