babel-loader doesn't work for webpack-dev-serv

2019-07-25 15:23发布

问题:

var path = require("path");
module.exports = {
    entry: "./src/index.js",
    output: {
        filename: "index.js",
        path: path.resolve(__dirname, "./built/"),
        publicPath: "/built/"
    },
    plugins: [],
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: "babel-loader"
            },
            {
                test: /\.vue$/,
                loader: "vue-loader",
                options: {
                }
            }
        ]
    }
};

With the above configuration,if I run webpack,it will get a correct result,but if I run webpack-dev-server,the source code in index.js will not been transpiled to ES5.In other words,babel-loader only works when webpack,but not webpack-dev-server.

why?

回答1:

Sounds like you're missing babel-register.

$ npm i --save-dev babel-register and add require('babel-register'); to the very top of your entry file (index.js).

See similar issue here: Making export default work with Babel, webpack and Node.js



回答2:

If you add a script like "dev": "webpack-dev-server" and then execute it with npm run dev or similar, it will execute the webpack-dev-server installed locally in your project's node_modules.

BUT if you've forgotten to add it to your project's dependencies, and you for some reason have a globally installed webpack-dev-server, it'll run that instead.

This caused the confusion described in the original question for me. The solution was, therefore, to install webpack-dev-server in my project with npm install --save-dev webpack-dev-server.