gpt4 book ai didi

javascript - webpack: 'import' 不工作,而 'require' 工作正常

转载 作者:行者123 更新时间:2023-12-02 14:30:58 25 4
gpt4 key购买 nike

我在使用 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-插件)。

我浏览了数十个论坛,但尚未找到解决方案。

最佳答案

问题是 ESLint - 而不是 webpack。

当你像这样在 webpack 中使用别名时

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

并且您正在以这种方式导入

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

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

要使其正常工作,您必须使用 "import/no-unresolved": 0 告诉 ESLint 忽略某些规则。这似乎没问题,因为如果导入的文件实际上丢失了,webpack 会自行报告错误。

关于javascript - webpack: 'import' 不工作,而 'require' 工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37833128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com