https://blog.csdn.net/hangmine/article/details/78569368
开始之前:
1.保证node.js是最新LTS版本
2.用管理员身份打开cmd
3.尽量用npm安装,如果报错再尝试用cnpm
初始化项目文件夹,创建package.json文件:
- npm init
项目目录安装webpack:
- npm install --save-dev webpack
创建两个文件夹和二个文件:
index.html --放在dist文件夹中;(并引入bundle.js和style.css)
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <link rel="stylesheet" href="style.css">
- <title>Document</title>
- </head>
- <body>
- </body>
- <script src="bundle.js">
- </script>
- </html>
main.js-- 放在src文件夹中;
在package.json文件配置wepack和webpack-dev-server的命令:
- "scripts": {
- "test": "echo \"Error: no test specified\" && exit 1",
- "start": "webpack",
- "server": "webpack-dev-server --open"
- }
安装相关组件:
本地服务器:
- cnpm install --save-dev webpack-dev-server
babel相关依赖包:
- cnpm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react
CSS相关依赖包:
- cnpm install --save-dev style-loader css-loader postcss-loader autoprefixer sass-loader file-loader url-loader node-sass extract-text-webpack-plugin
第三方插件相关依赖包:
- cnpm install --save-dev jquery bootstrap expose-loader
创建webpack.config.js文件并配置:
- const webpack = require('webpack');
- const ExtractTextPlugin = require('extract-text-webpack-plugin');
- module.exports = {
- devtool: 'eval-source-map',
- entry: __dirname + "/src/main.js",
- output: {
- path: __dirname + "/dist",
- filename: "bundle.js"
- },
- devServer: {
- contentBase: "./dist", //本地服务器所加载的页面所在的目录
- historyApiFallback: true, //不跳转
- inline: true //实时刷新
- },
- module: {
- rules: [{
- test: require.resolve('jquery'),
- loader: 'expose-loader?jQuery!expose-loader?$'
- },
- {
- test: /(\.jsx|\.js)$/,
- use: {
- loader: "babel-loader",
- options: {
- presets: [
- "react", "es2015"
- ]
- }
- },
- exclude: /node_modules/
- },
- {
- test: /\.css/,
- use: ExtractTextPlugin.extract({
- fallback: 'style-loader',
- use: [{
- loader: 'css-loader?modules: true'
- },
- {
- loader: 'postcss-loader',
- options: {
- sourceMap: true,
- config: {
- path: 'postcss.config.js' // 这个得在项目根目录创建此文件
- }
- }
- }
- ]
- })
- },
- {
- test: /\.(scss|sass)$/,
- loader: ExtractTextPlugin.extract({
- fallback: 'style-loader',
- use: ['css-loader', 'postcss-loader', 'sass-loader']
- })
- },
- {
- test: /\.(gif|jpg|png|woff|svg|eot|ttf)\??.*$/,
- loader: 'url-loader?name=[path][name].[ext]'
- }
- ]
- },
- plugins: [
- new webpack.LoaderOptionsPlugin({
- options: {
- postcss: [
- require('autoprefixer')()
- ]
- }
- }),
- new ExtractTextPlugin("style.css")
- ]
- };
创建postcss.config.js文件并添加autoprofixer插件:
- // postcss.config.js
- module.exports = {
- plugins: [
- require('autoprefixer')
- ]
- };
然后在main.js里import:(注意:ES6语法,相对路径引用当前文件夹必须加./!!)
- import $ from 'expose-loader?$!jquery';
- import 'bootstrap';
- import 'bootstrap/dist/css/bootstrap.min.css';