[英]Problem with import / export ts modules in webpack
因此,我嘗試為使用 typescript 的網站制作 webpack 配置。 一切正常,但是當我想導入一些不是條目的 ts 文件時,出現錯誤:
Module not found: Error: Can't resolve '../module' in '/Users/user/Projects/Node/project/src/script'
我怎樣才能解決這個問題? 我猜 webpack 不知道我嘗試導入的文件,但我應該怎么做? 我正在學習 webpack,但在 web 上找不到任何東西。
文件夾結構:
/src
/util
-module.ts
/script
-index.ts
...
原因(index.ts):
import { sth } from "../util/module"; // <-----------
console.log(sth);
模塊:
export const sth = "Hello World!";
webpack 配置:
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const path = require("path");
const fs = require("fs");
const generateEntry = () => {
const entry = {};
const entryDir = path.resolve(__dirname, "src/script");
fs.readdirSync(entryDir).forEach((file) => {
const filename = file.split(".")[0];
entry[filename] = path.resolve(__dirname, "src/script", file);
});
return entry;
};
const generateTemplates = () => {
const templates = [];
const templatesDir = path.resolve(__dirname, "src/templates");
fs.readdirSync(templatesDir).forEach((file) => {
const filename = file.split(".")[0];
templates.push(
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "src/templates", file),
chunks: [filename]
})
);
});
return templates;
};
module.exports = {
entry: generateEntry(),
output: {
publicPath: "",
path: path.resolve(__dirname, "./dist"),
filename: "script/[name].[contenthash].js"
},
module: {
rules: [
{
test: /\.ts$/i,
loader: "ts-loader",
exclude: /node_modules/
},
{
test: /\.scss$/i,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
exclude: /node_modules/
},
{
test: /\.html$/i,
loader: "html-loader"
},
{
test: /\.(png|jpe?g|gif)$/i,
loader: "file-loader",
options: {
outputPath: "static",
name: "[name].[contenthash].[ext]"
}
}
]
},
devServer: {
contentBase: path.resolve(__dirname, "dist"),
compress: false,
port: 8654
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: "style/[name].[contenthash].css"
})
].concat(generateTemplates())
};
所以添加
resolve: {
extensions: ['.ts']
}
在 webpack 配置中為我修復了這個問題:))))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.