Import txt files as string into your next.js App

 import file from './xxx.txt'

Webpack 5 has 'Asset Modules' to allow you to import assets without configuring loaders now.

Next.js use Webpack 5 internally, so we can use 'source assets' to import txt files as strings.

Two steps to let you be able to import a txt file as a string.

custom Webpack config for next.js


config.module.rules.push({
test: /\.txt$/i,
type: 'asset/source'
})

declare txt as a module for typescript

Wildcard module declarations can be used to cover these cases.

declare module '*.txt' {
const content: string;
export default content;
}

example

import t1 from './1.txt'
console.log(t1)

output

event - compiled successfully
离开罪之路的人蒙祝福,
他不去随从恶人的计谋,
他不会站在罪人的道路上,
也不去坐好讥笑人的座位,
他喜爱的是耶和华律法,
昼夜默诵的也是他律法。

The full commit to enabling import txt files in your next.js app


references


https://webpack.js.org/guides/asset-modules/#source-assets
https://webpack.js.org/concepts/#loaders
https://www.typescriptlang.org/docs/handbook/modules.html#wildcard-module-declarations
https://nextjs.org/docs/api-reference/next.config.js/custom-webpack-config

Comments

Popular posts from this blog

react-native run-android : do not build/update modified code(App.js)

react-native run-android : sun.security.provider.cert path.SunCertPathBuilderException : unable to find valid certification path to req uested target

How to fix error : no module named sendgrid when try to use sendgrid python lib in PHP.