webpack:' import'没有工作而需要'工作正常

时间:2016-06-15 10:41:18

标签: javascript node.js ecmascript-6 webpack babeljs

使用webpack我有一个奇怪的问题。

这是我的webpack.config.js:

import webpack from "webpack";
import path from "path";

//not working: import ExtractTextPlugin from "extract-text-webpack-plugin";
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const GLOBALS = {
    "process.env.NODE_ENV": JSON.stringify("production"),
    __DEV__: false
};

export default {
    debug: true,
    devtool: "source-map",
    noInfo: true,
    entry: "./src/bootstrap",
    target: "web",
    output: {
        path: path.join(__dirname, "dist"),
        publicPath: "/",
        filename: "bundle.js"
    },
    resolve: {
        root: path.resolve(__dirname),
        alias: {
            "~": "src"
        },
        extensions: ["", ".js", ".jsx"]
    },
    plugins: [
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.DefinePlugin(GLOBALS),
        new ExtractTextPlugin("styles.css"),
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.UglifyJsPlugin()
    ],
    module: {
        loaders: [
            { test: /\.jsx?$/, include: path.join(__dirname, "src"), loaders: ["babel"] },
            { test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: "file" },
            { test: /\.(woff|woff2)$/, loader: "file-loader?prefix=font/&limit=5000" },
            { test: /\.ttf(\?v=\d+.\d+.\d+)?$/, loader: "file-loader?limit=10000&mimetype=application/octet-stream" },
            { test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: "file-loader?limit=10000&mimetype=image/svg+xml" },
            { test: /\.(jpe?g|png|gif)$/i, loaders: ["file"] },
            { test: /\.ico$/, loader: "file-loader?name=[name].[ext]" },
            {
                test: /(\.css|\.scss)$/,
                loader: ExtractTextPlugin.extract("css?sourceMap!sass?sourceMap")
            }
        ]
    }
};

如您所见:我设置了一个指向"~"目录的别名"src"

根据webpack文档,我应该能够以这种方式导入模块:

import { ServiceStub } from "~/utilities/service-stub";

提示:文件service-stub.js位于此处:[__dirname]/src/utilities/service-stub.js

但是,这不起作用,因为webpack会抛出错误("找不到路径。")。

当我使用require代替import时,一切正常:

const { ServiceStub } = require("~/utilities/service-stub");

同样的问题出现在webpack.config.js本身:

import webpack from "webpack";
import path from "path";

//not working: import ExtractTextPlugin from "extract-text-webpack-plugin";
const ExtractTextPlugin = require("extract-text-webpack-plugin");

这里有些模块可以很好地导入import(模块webpackpath),有些模块不能导入(模块extract-text-webpack-plugin)。

我在几十个论坛上工作过,但还没找到任何解决方案。

1 个答案:

答案 0 :(得分:2)

问题是ESLint - 而不是webpack。

当您在webpack中使用别名时

resolve: {
    root: path.resolve(__dirname),
    alias: {
        "~": "src"
    },
    extensions: ["", ".js", ".jsx"]
}

你正在以这种方式导入

import { ServiceStub } from "~/services/service-stub";

ESLint无法解析别名并报告错误。

要使其正常运行,您必须告诉ESLint忽略某些带有"import/no-unresolved": 0的规则。这似乎没问题,因为如果实际上缺少导入的文件,webpack本身会报告错误。